package main
import (
"bytes"
"fmt"
"log"
"time"
consulapi "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/api/watch"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
)
var (
defaultConfig *viper.Viper
consulAddress string
consulPath string
)
func initConfig() *viper.Viper {
consulAddress = "http://192.168.100.19:8500"
consulPath = "config/v1/local"
defaultConfig = viper.New()
defaultConfig.SetConfigType("yaml")
consulClient, err := consulapi.NewClient(&consulapi.Config{Address: consulAddress})
if err != nil {
log.Fatalln("consul连接失败:", err)
}
kv, _, err := consulClient.KV().Get(consulPath, nil)
if err != nil {
log.Fatalln("consul获取配置失败:", err)
}
err = defaultConfig.ReadConfig(bytes.NewBuffer(kv.Value))
if err != nil {
log.Fatalln("Viper解析配置失败:", err)
}
go watchConfig()
return defaultConfig
}
func watchConfig() {
time.Sleep(time.Second * 10)
params := make(map[string]interface{})
params["type"] = "key"
params["key"] = consulPath
w, err := watch.Parse(params)
if err != nil {
log.Fatalln(err)
}
w.Handler = func(u uint64, i interface{}) {
kv := i.(*consulapi.KVPair)
hotconfig := viper.New()
hotconfig.SetConfigType("yaml")
err = hotconfig.ReadConfig(bytes.NewBuffer(kv.Value))
if err != nil {
log.Fatalln("Viper解析配置失败:", err)
}
defaultConfig = hotconfig
}
err = w.Run(consulAddress)
if err != nil {
log.Fatalln("监听consul错误:", err)
}
}
func GetConfig() *viper.Viper {
if defaultConfig == nil {
defaultConfig = initConfig()
}
return defaultConfig
}
func main() {
ReadOne()
go func() {
for {
host := GetConfig().GetString("store.bicycle.color")
fmt.Println("consul===", host)
time.Sleep(time.Second * 10)
}
}()
select {}
}
func ReadOne() {
runtimeConfig := viper.New()
runtimeConfig.AddRemoteProvider("consul", "http://192.168.100.19:8500", "config/v1/local")
runtimeConfig.SetConfigType("yaml")
err := runtimeConfig.ReadRemoteConfig()
if err != nil {
log.Fatalln("viper read:", err)
}
err = runtimeConfig.WatchRemoteConfigOnChannel()
if err != nil {
log.Fatalln("viper watch err:", err)
}
go func() {
for {
host := runtimeConfig.GetString("store.bicycle.color")
fmt.Println("viper=====", host)
time.Sleep(time.Second * 10)
}
}()
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构