103 lines
2.4 KiB
Go
103 lines
2.4 KiB
Go
// Package etcd...
|
|
//
|
|
// Description : etcd...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2021-11-23 12:09 下午
|
|
package etcd
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"go.etcd.io/etcd/api/v3/mvccpb"
|
|
clientv3 "go.etcd.io/etcd/client/v3"
|
|
)
|
|
|
|
// Put put数据
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 12:09 下午 2021/11/23
|
|
func (wc *WrapperClient) Put(ctx context.Context, key string, val string, operateTimeout time.Duration) (*clientv3.PutResponse, error) {
|
|
if operateTimeout <= 0 {
|
|
operateTimeout = DefaultPutTimeout
|
|
}
|
|
var (
|
|
cancel context.CancelFunc
|
|
err error
|
|
response *clientv3.PutResponse
|
|
)
|
|
if nil == ctx {
|
|
ctx = context.Background()
|
|
}
|
|
ctx, cancel = context.WithTimeout(ctx, operateTimeout)
|
|
response, err = wc.client.Put(ctx, key, val)
|
|
cancel()
|
|
return response, err
|
|
}
|
|
|
|
// GetWithOption 使用各种option选项读取数据
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 11:17 上午 2021/11/24
|
|
func (wc *WrapperClient) GetWithOption(ctx context.Context, key string, operateTimeout time.Duration, optionList ...clientv3.OpOption) (
|
|
[]*mvccpb.KeyValue,
|
|
error,
|
|
) {
|
|
if operateTimeout <= 0 {
|
|
operateTimeout = DefaultGetTimeout
|
|
}
|
|
var (
|
|
cancel context.CancelFunc
|
|
err error
|
|
result *clientv3.GetResponse
|
|
)
|
|
if nil == ctx {
|
|
ctx = context.Background()
|
|
}
|
|
ctx, cancel = context.WithTimeout(context.Background(), operateTimeout)
|
|
defer cancel()
|
|
if result, err = wc.client.Get(ctx, key, optionList...); err != nil {
|
|
return nil, err
|
|
}
|
|
return result.Kvs, nil
|
|
}
|
|
|
|
// Get 读取数据,按照key精确匹配
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 12:09 下午 2021/11/23
|
|
func (wc *WrapperClient) Get(ctx context.Context, key string, operateTimeout time.Duration) (
|
|
[]*mvccpb.KeyValue,
|
|
error,
|
|
) {
|
|
return wc.GetWithOption(ctx, key, operateTimeout)
|
|
}
|
|
|
|
// GetWithPrefix 使用key前缀查找
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 10:58 上午 2021/11/24
|
|
func (wc *WrapperClient) GetWithPrefix(ctx context.Context, keyPrefix string, operateTimeout time.Duration) (
|
|
map[string]*mvccpb.KeyValue,
|
|
error,
|
|
) {
|
|
var (
|
|
result []*mvccpb.KeyValue
|
|
err error
|
|
)
|
|
if result, err = wc.GetWithOption(ctx, keyPrefix, operateTimeout, clientv3.WithPrefix()); nil != err {
|
|
return make(map[string]*mvccpb.KeyValue), err
|
|
}
|
|
formatResult := make(map[string]*mvccpb.KeyValue)
|
|
for _, item := range result {
|
|
formatResult[string(item.Key)] = item
|
|
}
|
|
return formatResult, nil
|
|
}
|