读取数据增加按照前缀匹配查询

This commit is contained in:
2021-11-24 11:26:02 +08:00
parent 7bef73334c
commit 1da5793132
3 changed files with 57 additions and 8 deletions

View File

@ -37,12 +37,12 @@ func Put(ctx context.Context, key string, val string, operateTimeout time.Durati
return err
}
// Get 读取数据
// GetWithOption 使用各种option选项读取数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:09 下午 2021/11/23
func Get(ctx context.Context, key string, operateTimeout time.Duration) (
// Date : 11:17 上午 2021/11/24
func GetWithOption(ctx context.Context, key string, operateTimeout time.Duration, optionList ...clientv3.OpOption) (
[]*mvccpb.KeyValue,
error,
) {
@ -57,11 +57,45 @@ func Get(ctx context.Context, key string, operateTimeout time.Duration) (
if nil == ctx {
ctx = context.Background()
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
result, err = Client.Get(ctx, key)
cancel()
if err != nil {
ctx, cancel = context.WithTimeout(context.Background(), operateTimeout)
defer cancel()
if result, err = 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 Get(ctx context.Context, key string, operateTimeout time.Duration) (
[]*mvccpb.KeyValue,
error,
) {
return GetWithOption(ctx, key, operateTimeout)
}
// GetWithPrefix 使用key前缀查找
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 10:58 上午 2021/11/24
func GetWithPrefix(ctx context.Context, keyPrefix string, operateTimeout time.Duration) (
map[string]*mvccpb.KeyValue,
error,
) {
var (
result []*mvccpb.KeyValue
err error
)
if result, err = 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
}