增加设置一次性有效租约的方法
This commit is contained in:
parent
0b5e55cefd
commit
29cb4a4fba
43
middleware/etcd/lease.go
Normal file
43
middleware/etcd/lease.go
Normal file
@ -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
|
||||
}
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user