你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
在本快速入门中,你将增强基本的 Go 控制台应用程序,以便从 Azure 应用配置动态刷新配置。 这使得您的应用程序能够在无需重启的情况下捕捉配置变更。
先决条件
- 完成 快速入门:使用 Azure 应用配置创建 Go 控制台应用 作为本快速入门的起点
从应用配置重载数据
打开
appconfig.go
文件。 在loadAzureAppConfiguration
函数内,更新options
以启用刷新。 每当 Go 提供程序检测到任何所选键值(从 配置 开始且没有标签)发生更改时,Go 提供程序都会重新加载整个配置。 有关监视配置更改的详细信息,请参阅 配置刷新的最佳做法。options := &azureappconfiguration.Options{ Selectors: []azureappconfiguration.Selector{ { KeyFilter: "Config.*", }, }, TrimKeyPrefixes: []string{"Config."}, RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{ Enabled: true, }, }
小窍门
可以设置
Interval
属性RefreshOptions
以指定配置刷新之间的最短时间。 在此示例中,使用默认值 30 秒。 如果需要减少对应用配置存储的请求数量,请调整为更高的值。打开该文件
unmarshal_sample.go
并将以下代码添加到主函数:// Existing code in unmarshal_sample.go // ... ... fmt.Printf("Timeout: %d seconds\n", config.App.Settings.Timeout) fmt.Printf("Retry Count: %d\n", config.App.Settings.RetryCount) // Register refresh callback to update and display the configuration provider.OnRefreshSuccess(func() { // Re-unmarshal the configuration err := appCfgProvider.Unmarshal(&updatedConfig, nil) if err != nil { log.Printf("Error unmarshalling updated configuration: %s", err) return } // Display the updated configuration displayConfig(config) }) // 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 } }
运行应用程序
运行应用程序:
go run unmarshal_sample.go
使应用程序保持运行。
导航到您的应用配置存储并更新
Config.Message
键的值。密钥 价值 内容类型 Config.Message Hello World - 已更新! 留空 观察控制台应用程序 - 在 30 秒内,应检测更改并显示更新的配置。
清理资源
如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。
重要
删除资源组的操作不可逆。 将永久删除资源组以及其中的所有资源。 请确保不要意外删除错误的资源组或资源。 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。
- 登录到 Azure 门户,然后选择“资源组”。
- 在按名称筛选框中,输入资源组的名称。
- 在结果列表中,选择资源组名称以查看概述。
- 选择“删除资源组”。
- 系统会要求确认是否删除资源组。 重新键入资源组的名称进行确认,然后选择“删除”。
片刻之后,将会删除该资源组及其所有资源。