1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
base.go 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-10-22 01:06 . rpc ,排序权重
package consul
import (
"fmt"
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/discovery/config"
"gitee.com/h79/goutils/discovery/service"
consul "github.com/hashicorp/consul/api"
)
type Base struct {
client *consul.Client
watcher *Watcher
}
func (base *Base) kvSet(data service.Data) error {
if base.client == nil {
return fmt.Errorf("client is null, error")
}
if data.Path == "" || data.Service == "" {
return fmt.Errorf("data error: %v", data)
}
kv := &consul.KVPair{
Key: data.ToKey(),
Flags: 0,
Value: []byte(data.Value)}
_, err := base.client.KV().Put(kv, nil)
return err
}
func (base *Base) kvGet(key service.Key) ([]*service.Data, error) {
if base.client == nil {
return nil, fmt.Errorf("client is null, error")
}
kv, _, err := base.client.KV().Get(key.ToKey(), nil)
if err != nil {
return nil, err
}
var kvs []*service.Data
kvs = append(kvs, &service.Data{
Key: service.NewKey(kv.Key),
Value: string(kv.Value),
})
return kvs, nil
}
// Set interface
func (base *Base) Set(data service.Data) error {
if err := base.kvSet(data); err != nil {
logger.Error("Consul.build: set data, err= %+v", err)
return err
}
return nil
}
// Get interface
func (base *Base) Get(key service.Key) ([]*service.Data, error) {
kvs, err := base.kvGet(key)
if err != nil {
logger.Error("Consul.build: get data, err= %+v", err)
return nil, err
}
return kvs, nil
}
func (base *Base) AttachWatcher(watcher *Watcher) {
base.watcher = watcher
}
func NewClientWithPoints(eps config.EndPoints) (*consul.Client, error) {
eps.Servers.ToWeight()
for _, addr := range eps.Servers.Array() {
cfg := consul.DefaultConfig()
cfg.Address = addr //host:port
client, err := consul.NewClient(cfg)
if err == nil {
return client, nil
}
}
return nil, result.Error(result.ErrServiceInternal,
fmt.Sprintf("CONSUL.CLIENT: create consul client failure"))
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.90

搜索帮助