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"
|
|
|
|
)
|
|
|
|
|
2022-01-11 17:10:38 +08:00
|
|
|
var (
|
2022-01-19 19:39:04 +08:00
|
|
|
EndPoints = "ENDPOINTS"
|
|
|
|
//EndAddress = "etcd." + env.Namespace + ":2379"
|
|
|
|
EndAddress = "127.0.0.1:2379"
|
2022-01-11 00:48:03 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
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()
|
2022-01-11 17:10:38 +08:00
|
|
|
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*3)
|
2022-01-11 00:48:03 +08:00
|
|
|
defer cancel()
|
|
|
|
if getResp, err := kv.Get(ctx, key, clientV3.WithPrefix()); err == nil {
|
2022-01-11 04:00:39 +08:00
|
|
|
if len(getResp.Kvs) > 0 {
|
|
|
|
return string(getResp.Kvs[0].Value), nil
|
2022-01-11 00:48:03 +08:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return "", errors.New("etcd 连接超时")
|
|
|
|
}
|
|
|
|
return "", errors.New(fmt.Sprintf("没有根据%v找到对应value", key))
|
|
|
|
}
|