package etcd import ( "context" "fmt" "git.icechen.cn/monorepo/backend/pkg/env" "github.com/pkg/errors" clientV3 "go.etcd.io/etcd/client/v3" "strings" "time" ) const ( EndPoints = "ENDPOINTS" EndAddress = "etcd1:2379" ) var ( client *clientV3.Client config clientV3.Config err error ) func connect() error { envDefault := env.GetEnvDefault(EndPoints, EndAddress) ends := strings.Split(envDefault, ",") config = clientV3.Config{ Endpoints: ends, DialTimeout: 5 * time.Second, } if client, err = clientV3.New(config); err != nil { return errors.WithMessage(err, "etcd 连接错误") } return nil } func GetValue(key string) (string, error) { if err = connect(); err != nil { return "", err } kv := clientV3.NewKV(client) defer client.Close() ctx, cancel := context.WithTimeout(context.TODO(), time.Minute*3) defer cancel() if getResp, err := kv.Get(ctx, key, clientV3.WithPrefix()); err == nil { if len(getResp.Kvs) > 0 { return string(getResp.Kvs[0].Value), nil } } else { return "", errors.New("etcd 连接超时") } return "", errors.New(fmt.Sprintf("没有根据%v找到对应value", key)) }