使用Golang基于Etcd可构建轻量级配置中心,支持配置存储、动态更新、多环境管理、版本控制和访问控制;通过HTTP接口实现配置获取与监听,客户端利用goroutine实时感知变更,结合缓存、批量查询与健康检查优化生产可用性。

在微服务架构中,配置中心是核心组件之一。它解决了服务配置分散、变更困难、一致性差等问题。Golang 因其高性能和简洁语法,成为实现配置中心的理想语言。下面介绍如何使用 Golang 构建一个轻量级的微服务配置中心。
一个实用的配置中心应具备以下能力:
Etcd 是分布式系统常用的键值存储,天然支持 Watch 机制,适合做配置中心后端。
使用 go.etcd.io/etcd/clientv3 包操作 Etcd:
立即学习“go语言免费学习笔记(深入)”;
package main <p>import ( "context" "log" "net/http" "time"</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">"go.etcd.io/etcd/clientv3"
)
var etcdClient *clientv3.Client
func init() { var err error etcdClient, err = clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379"}, DialTimeout: 5 * time.Second, }) if err != nil { log.Fatal("连接 Etcd 失败:", err) } }
// 获取配置 func getConfig(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") ctx, cancel := context.WithTimeout(context.Background(), time.Second) resp, err := etcdClient.Get(ctx, key) cancel() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } for _, ev := range resp.Kvs { w.Write(ev.Value) return } http.NotFound(w, r) }
// 监听配置变化(供客户端调用) func watchConfig(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") watcher := etcdClient.Watch(context.Background(), key) w.Header().Set("Content-Type", "text/event-stream") for wr := range watcher { for _, ev := range wr.Events { w.Write([]byte("data: " + string(ev.Kv.Value) + "\n\n")) w.(http.Flusher).Flush() } } }
启动 HTTP 服务:
func main() {
http.HandleFunc("/config/get", getConfig)
http.HandleFunc("/config/watch", watchConfig)
log.Println("配置中心启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
服务启动时从配置中心拉取初始配置,并开启 goroutine 监听变更:
func loadConfig(key string, config *string) {
// 初始获取
resp, err := http.Get("http://config-center:8080/config/get?key=" + key)
if err != nil {
log.Fatal("获取配置失败:", err)
}
body, _ := io.ReadAll(resp.Body)
*config = string(body)
resp.Body.Close()
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 持续监听
go func() {
for {
resp, err := http.Get("http://config-center:8080/config/watch?key=" + key)
if err != nil {
time.Sleep(time.Second)
continue
}
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
newVal := strings.TrimPrefix(line, "data: ")
if *config != newVal {
log.Printf("配置更新: %s -> %s", *config, newVal)
*config = newVal
// 可触发 reload 逻辑
}
}
}
resp.Body.Close()
}
}()}
基本上就这些。用 Golang 实现配置中心不复杂但容易忽略细节,关键是稳定性和实时性要兼顾。结合 Etcd 和标准库就能快速搭建出可用的方案,后续再根据业务扩展权限、审计等功能。
以上就是如何用Golang实现微服务配置中心_Golang 配置中心开发与实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号