共用方式為


教學課程:在 Go 控制台應用程式中啟用動態設定重新整理

在本快速入門中,您將提升基本的 Go 命令列應用程式,以動態地重新整理來自 Azure 應用程式組態的設定。 這可讓您的應用程式即時接收設定變更,而不需要重新啟動。

先決條件

從應用程式設定重新載入資料

  1. 開啟檔案 appconfig.go。 在函式 loadAzureAppConfiguration 內,更新 options 以啟用重新整理。 每當 Go 提供者偵測到任何選取的鍵值對變更時,就會重載整個組態(選取的項目從 Config. 開始且沒有標籤)。 如需監視組態變更的詳細資訊,請參閱 設定重新整理的最佳做法

    options := &azureappconfiguration.Options{
        Selectors: []azureappconfiguration.Selector{
            {
                KeyFilter: "Config.*",
            },
        },
        TrimKeyPrefixes: []string{"Config."},
        RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{
            Enabled:  true,
        },
    }
    

    小提示

    您可以設定 IntervalRefreshOptions 屬性,以指定組態重新整理之間的最短時間。 在此範例中,您必須使用 30 秒的預設值。 如果您需要減少對應用程式組態存放區提出的要求數目,請調整為較高的值。

  2. 開啟 檔案 main.go ,並將下列程式代碼新增至您的 main 函式:

    // Existing code in main.go
    // ... ...
     fmt.Println("\nRaw JSON Configuration:")
     fmt.Println("------------------------")
     fmt.Println(string(jsonBytes))
    
    // Register refresh callback to update the configuration
     provider.OnRefreshSuccess(func() {
     	var updatedConfig Config
     	// Re-unmarshal the configuration
     	err := provider.Unmarshal(&updatedConfig, nil)
     	if err != nil {
     		log.Printf("Error unmarshalling updated configuration: %s", err)
     		return
     	}
    
     	fmt.Printf("Message: %s\n", updatedConfig.Message)
     })
    
    // Setup a channel to listen for termination signals
    done := make(chan os.Signal, 1)
    signal.Notify(done, syscall.SIGINT, syscall.SIGTERM)
    
    fmt.Println("\nWaiting for configuration changes...")
    fmt.Println("(Update values in Azure App Configuration to see refresh in action)")
    fmt.Println("Press Ctrl+C to exit")
    
    // Start a ticker to periodically trigger refresh
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()
    
    // Keep the application running until terminated
    for {
        select {
        case <-ticker.C:
            // Trigger refresh in background
            go func() {
                ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
                defer cancel()
    
                if err := provider.Refresh(ctx); err != nil {
                    log.Printf("Error refreshing configuration: %s", err)
                }
            }()
        case <-done:
            fmt.Println("\nExiting...")
            return
        }
    }
    

執行應用程式

  1. 執行應用程式:

     go mod tidy
     go run .
    
  2. 使應用程式持續運行。

  3. 流覽至您的應用程式組態存放區,並更新金鑰的值 Config.Message

    鑰匙 價值觀 內容類型
    Config.Message Hello World - 已更新! 保留空白
  4. 觀察您的主控台應用程式 - 在 30 秒內,應該偵測變更並顯示更新的組態。

清理資源

如果您不想繼續使用本文中建立的資源,請刪除在此處建立的資源群組,以避免產生費用。

這很重要

刪除資源群組是無法回復的動作。 資源群組和其中的所有資源都將被永久刪除。 請確定您不會誤刪錯誤的資源群組或資源。 如果您是在包含其他您想保留資源的資源群組中建立本文的資源,則應該從各自的面板中逐一刪除每個資源,而不用刪除整個資源群組。

  1. 登入 Azure 入口網站,然後選取 [資源群組]
  2. 在 [依名稱篩選] 方塊中,輸入您資源群組的名稱。
  3. 在結果清單中,選取資源群組名稱以查看概觀。
  4. 選擇 ,刪除資源群組
  5. 系統將會要求您確認是否刪除資源群組。 輸入您資源群組的名稱以進行確認,然後選取 [刪除]

不久後,系統便會刪除該資源群組及其所有的資源。