前言
上节已经把两个服务都搭建了起来,记得流程里说的是,服务启动的时候,获取配置中心里面读取信息,刚好EDCT也支持配置中心等功能。
配置信息写入Ectd:
因为之前Ectd是通过Docker启动的,需要进入到里面写入一些信息,用户读取测试:
提交相关信息:
命令:
/bin # etcdctl put dbhost 127.0.0.1
/bin # etcdctl put dbpws xiaozhong
结果:
[root@localhost ~]# docker exec -it etcd2 sh
/ # export ETCDCTL_API=3
/bin # etcdctl version
etcdctl version: 3.3.8
API version: 3.3
/bin #
/bin # etcdctl put dbhost 127.0.0.1 dbname xiaozhong dbpws xiaozhong
OK
/bin #
/bin # etcdctl get dbhost
dbhost
127.0.0.1
/bin #
使用代码从Ectd读取信息:
定义一个读取工具类:
image.png
package utils
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
)
func GetKey(etcdAddr string,key string)(value string){
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{etcdAddr},
})
if err != nil {
fmt.Println("connect etcd failed, err:%s", err.Error())
return
}
defer cli.Close()
kv := clientv3.NewKV(cli)
resp, err := kv.Get(context.TODO(), key)
if err != nil {
fmt.Println("get etcd key failed, key:%s, err:%s", key, err.Error())
return "enimt"
}
for _, ev := range resp.Kvs {
value = string(ev.Value)
}
return value
}
测试我们的读取情况,在启动用户服务的时候,从注册中心读取信息。
package main
import (
"github.com/micro/go-micro/v2"
log "github.com/micro/go-micro/v2/logger"
"user/handler"
user "user/proto/user"
"user/utils"
)
func main() {
// New Service
println(utils.GetKey("192.168.219.130:2379","dbhost"))
println(utils.GetKey("192.168.219.130:2379","dbname"))
println(utils.GetKey("192.168.219.130:2379","dbpws"))
service := micro.NewService(
micro.Name("go.micro.service.user"),
micro.Version("latest"),
)
// Initialise service
service.Init()
// Register Handler
user.RegisterUserHandler(service.Server(), new(handler.User))
// Run service
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
网友评论