etcd/string.go

103 lines
2.4 KiB
Go
Raw Normal View History

2023-02-06 16:53:02 +08:00
// 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"
2023-02-06 16:53:02 +08:00
)
// Put put数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:09 下午 2021/11/23
2023-08-15 13:30:56 +08:00
func (wc *WrapperClient) Put(ctx context.Context, key string, val string, operateTimeout time.Duration) (*clientv3.PutResponse, error) {
2023-02-06 16:53:02 +08:00
if operateTimeout <= 0 {
operateTimeout = DefaultPutTimeout
}
var (
2023-08-15 13:30:56 +08:00
cancel context.CancelFunc
err error
response *clientv3.PutResponse
2023-02-06 16:53:02 +08:00
)
if nil == ctx {
ctx = context.Background()
}
ctx, cancel = context.WithTimeout(ctx, operateTimeout)
2023-08-15 13:30:56 +08:00
response, err = wc.client.Put(ctx, key, val)
2023-02-06 16:53:02 +08:00
cancel()
2023-08-15 13:30:56 +08:00
return response, err
2023-02-06 16:53:02 +08:00
}
// GetWithOption 使用各种option选项读取数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:17 上午 2021/11/24
2023-08-15 12:56:49 +08:00
func (wc *WrapperClient) GetWithOption(ctx context.Context, key string, operateTimeout time.Duration, optionList ...clientv3.OpOption) (
2023-02-06 16:53:02 +08:00
[]*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()
2023-08-15 12:56:49 +08:00
if result, err = wc.client.Get(ctx, key, optionList...); err != nil {
2023-02-06 16:53:02 +08:00
return nil, err
}
return result.Kvs, nil
}
// Get 读取数据,按照key精确匹配
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:09 下午 2021/11/23
2023-08-15 12:56:49 +08:00
func (wc *WrapperClient) Get(ctx context.Context, key string, operateTimeout time.Duration) (
2023-02-06 16:53:02 +08:00
[]*mvccpb.KeyValue,
error,
) {
2023-08-15 12:56:49 +08:00
return wc.GetWithOption(ctx, key, operateTimeout)
2023-02-06 16:53:02 +08:00
}
// GetWithPrefix 使用key前缀查找
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 10:58 上午 2021/11/24
2023-08-15 12:56:49 +08:00
func (wc *WrapperClient) GetWithPrefix(ctx context.Context, keyPrefix string, operateTimeout time.Duration) (
2023-02-06 16:53:02 +08:00
map[string]*mvccpb.KeyValue,
error,
) {
var (
result []*mvccpb.KeyValue
err error
)
2023-08-15 12:56:49 +08:00
if result, err = wc.GetWithOption(ctx, keyPrefix, operateTimeout, clientv3.WithPrefix()); nil != err {
2023-02-06 16:53:02 +08:00
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
}