lease增加永久续期支持

This commit is contained in:
白茶清欢 2021-11-23 20:02:15 +08:00
parent 29cb4a4fba
commit a9eabd0f19
3 changed files with 62 additions and 0 deletions

View File

@ -44,3 +44,6 @@ type CancelWatcherHandler func(key string, data interface{})
// TimeoutWatcherHandler 超时之后的回调函数
type TimeoutWatcherHandler func(key string, timeout time.Duration)
// LeaseKeepALiveHandler 续期成功的处理
type LeaseKeepALiveHandler func(key string, leaseDetail *clientv3.LeaseKeepAliveResponse)

View File

@ -41,3 +41,42 @@ func LeaseOnce(ctx context.Context, key string, val string, ttl int64) error {
}
return nil
}
// LeaseKeepAliveForever 无限续租一个key
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 7:40 下午 2021/11/23
func LeaseKeepAliveForever(ctx context.Context, key string, val string, ttl int64, keepAliveHandler LeaseKeepALiveHandler) error {
if ttl <= 0 {
return errors.New("lease time must be more than 0")
}
if nil == ctx {
ctx = context.TODO()
}
var (
resp *clientv3.LeaseGrantResponse
respChan <-chan *clientv3.LeaseKeepAliveResponse
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())
}
// the key will be kept forever
if respChan, err = Client.KeepAlive(ctx, resp.ID); nil != err {
return errors.New("lease keep alive fail : " + err.Error())
}
// 监听 chan
for ka := range respChan {
if nil != keepAliveHandler {
keepAliveHandler(key, ka)
}
}
return nil
}

View File

@ -173,3 +173,23 @@ func TestLeaseOnce(t *testing.T) {
time.Sleep(time.Second)
}
}
// TestLeaseKeepAliveForever ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 7:54 下午 2021/11/23
func TestLeaseKeepAliveForever(t *testing.T) {
key := "lock"
keepAliveHandler := func(key string, data *clientv3.LeaseKeepAliveResponse) {
fmt.Println(key, data.ID, data.TTL, data.Size(), data.String())
}
go func() {
fmt.Println(LeaseKeepAliveForever(nil, key, "lock", 10, keepAliveHandler))
}()
for i := 0; i < 15; i++ {
r, e := Get(nil, key, 1)
fmt.Println("读取", r, e)
time.Sleep(time.Second)
}
}