From 0898107e92a531bdbe9543a5a68f272c2bfa394c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Nov 2021 12:31:45 +0800 Subject: [PATCH] =?UTF-8?q?etcd=E5=A2=9E=E5=8A=A0put=E4=B8=8Eget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/etcd/define.go | 9 ++++++ middleware/etcd/string.go | 67 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 middleware/etcd/string.go diff --git a/middleware/etcd/define.go b/middleware/etcd/define.go index 2184c68..f2f73fa 100644 --- a/middleware/etcd/define.go +++ b/middleware/etcd/define.go @@ -12,6 +12,7 @@ import ( "time" ) +// 初始化client各种默认配置 const ( // DefaultDialTimeout 默认超时时间 DefaultDialTimeout = 5 * time.Second @@ -24,3 +25,11 @@ const ( // DefaultMaxCallRecvMsgSize 客户端接受的响应题最大大小, 默认int32最大值, 和etcd默认值保持一致 DefaultMaxCallRecvMsgSize = math.MaxInt32 ) + +// 操作过程中各种默认配置 +const ( + // DefaultPutTimeout put 默认超时时间 + DefaultPutTimeout = time.Second + // DefaultGetTimeout get 默认超时时间 + DefaultGetTimeout = time.Second +) diff --git a/middleware/etcd/string.go b/middleware/etcd/string.go new file mode 100644 index 0000000..9186483 --- /dev/null +++ b/middleware/etcd/string.go @@ -0,0 +1,67 @@ +// 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 +} + +// Get 读取数据 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:09 下午 2021/11/23 +func Get(ctx context.Context, key string, operateTimeout time.Duration) ( + []*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(), time.Second) + result, err = Client.Get(ctx, key) + cancel() + if err != nil { + return nil, err + } + return result.Kvs, nil +}