fox/etcd/etcd.go
2025-05-25 23:13:59 +08:00

61 lines
1.3 KiB
Go

package etcd
import (
"encoding/json"
"fmt"
"github.com/fox/fox/log"
"sync"
)
type resultT[T any] struct {
Value T
Err error
}
type Registry[T INode] struct {
*etcdRegistryImpl
nodes sync.Map
}
func NewRegistry[T INode](endpoints []string, rootKey, username, password string) (*Registry[T], error) {
var err error
e := &Registry[T]{}
e.etcdRegistryImpl, err = newServiceRegistryImpl(endpoints, rootKey, username, password, e.saveNode)
return e, err
}
func (r *Registry[T]) Register(node INode) error {
bs, err := json.Marshal(node)
if err != nil {
return err
}
return r.etcdRegistryImpl.Register(node.EtcdKey(), string(bs))
}
// 获取当前服务
func (r *Registry[T]) saveNode(jsonBytes []byte) {
var tmp = resultT[T]{Err: nil}
if err := json.Unmarshal(jsonBytes, &tmp.Value); err != nil {
log.ErrorF(err.Error())
}
r.nodes.Store(tmp.Value.MapKey(), tmp.Value)
}
// 获取当前根节点下所有节点信息
func (r *Registry[T]) GetNodes() *sync.Map {
return &r.nodes
}
// 获取当前根节点下所有节点信息
func (r *Registry[T]) FindNode(key string) (T, error) {
var tmp = resultT[T]{Err: nil}
v, ok := r.nodes.Load(key)
if !ok {
return tmp.Value, fmt.Errorf("%v not exist", key)
}
if tmp.Value, ok = v.(T); ok {
return tmp.Value, nil
}
return tmp.Value, fmt.Errorf("%v 类型转换失败", key)
}