backend/pkg/etcd/etcd.go

54 lines
1.1 KiB
Go
Raw Normal View History

2022-01-11 00:48:03 +08:00
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 = "etcd: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.Second*3)
defer cancel()
if getResp, err := kv.Get(ctx, key, clientV3.WithPrefix()); err == nil {
for _, v := range getResp.Kvs {
return string(v.Value), nil
}
} else {
return "", errors.New("etcd 连接超时")
}
return "", errors.New(fmt.Sprintf("没有根据%v找到对应value", key))
}