From 29cb4a4fbac2dd05a6b05ad8f22d5d648401c4b2 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 19:39:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=AE=BE=E7=BD=AE=E4=B8=80?= =?UTF-8?q?=E6=AC=A1=E6=80=A7=E6=9C=89=E6=95=88=E7=A7=9F=E7=BA=A6=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/etcd/lease.go | 43 ++++++++++++++++++++++++++++++++++ middleware/etcd/string_test.go | 14 +++++++++++ 2 files changed, 57 insertions(+) create mode 100644 middleware/etcd/lease.go diff --git a/middleware/etcd/lease.go b/middleware/etcd/lease.go new file mode 100644 index 0000000..4cc8966 --- /dev/null +++ b/middleware/etcd/lease.go @@ -0,0 +1,43 @@ +// Package etcd ... +// +// Description : 租约相关操作 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-23 6:03 下午 +package etcd + +import ( + "context" + + "github.com/pkg/errors" + "go.etcd.io/etcd/clientv3" +) + +// LeaseOnce 申请一个一次性租约 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 6:06 下午 2021/11/23 +func LeaseOnce(ctx context.Context, key string, val string, ttl int64) error { + if ttl <= 0 { + return errors.New("lease time must be more than 0") + } + if nil == ctx { + ctx = context.TODO() + } + var ( + resp *clientv3.LeaseGrantResponse + err error + ) + // 创建一个5秒的租约 + if resp, err = Client.Grant(ctx, ttl); err != nil { + return errors.New("lease grant error : " + err.Error()) + } + + // ttl 秒钟之后, 这个key就会被移除 + if _, err = Client.Put(context.TODO(), key, val, clientv3.WithLease(resp.ID)); err != nil { + return errors.New("lease key put fail : " + err.Error()) + } + return nil +} diff --git a/middleware/etcd/string_test.go b/middleware/etcd/string_test.go index 031a7ad..c7f8c9a 100644 --- a/middleware/etcd/string_test.go +++ b/middleware/etcd/string_test.go @@ -159,3 +159,17 @@ func TestWatchKeyOnceForTimeout(t *testing.T) { WatchKeyOnce(nil, key, dealFunc, timeout, timeoutFunc) } + +// TestLeaseOnce ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 7:37 下午 2021/11/23 +func TestLeaseOnce(t *testing.T) { + key := "lock" + fmt.Println(LeaseOnce(nil, key, "lock", 10)) + for i := 0; i < 15; i++ { + fmt.Println(Get(nil, key, 1)) + time.Sleep(time.Second) + } +}