// Package etcd... // // Description : etcd... // // Author : go_developer@163.com<白茶清欢> // // Date : 2021-11-23 12:09 下午 package etcd import ( "context" "time" "github.com/coreos/etcd/mvcc/mvccpb" "go.etcd.io/etcd/clientv3" ) // Put put数据 // // Author : go_developer@163.com<白茶清欢> // // Date : 12:09 下午 2021/11/23 func Put(ctx context.Context, key string, val string, operateTimeout time.Duration) error { if operateTimeout <= 0 { operateTimeout = DefaultPutTimeout } var ( cancel context.CancelFunc err error ) if nil == ctx { ctx = context.Background() } ctx, cancel = context.WithTimeout(ctx, operateTimeout) _, err = Client.Put(ctx, key, val) cancel() return err } // GetWithOption 使用各种option选项读取数据 // // Author : go_developer@163.com<白茶清欢> // // Date : 11:17 上午 2021/11/24 func 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 = 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 }