增加删除key的方法

This commit is contained in:
白茶清欢 2021-11-24 14:18:31 +08:00
parent 4cbb2a9667
commit 9ff498706c
3 changed files with 78 additions and 0 deletions

View File

@ -34,6 +34,8 @@ const (
DefaultPutTimeout = time.Second
// DefaultGetTimeout get 默认超时时间
DefaultGetTimeout = time.Second
// DefaultDeleteTimeout 删除的超时时间
DefaultDeleteTimeout = time.Second
)
// WatcherHandler 监听key变化的处理函数

54
middleware/etcd/delete.go Normal file
View File

@ -0,0 +1,54 @@
// Package etcd...
//
// Description : 删除相关操作
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-11-24 12:42 下午
package etcd
import (
"context"
"errors"
"time"
"go.etcd.io/etcd/clientv3"
)
// DeleteWithOption ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2:02 下午 2021/11/24
func DeleteWithOption(ctx context.Context, key string, timeout time.Duration, optionList ...clientv3.OpOption) (*clientv3.DeleteResponse, error) {
if nil == ctx {
ctx = context.Background()
}
if timeout <= 0 {
timeout = DefaultDeleteTimeout
}
var (
cancelFunc context.CancelFunc
deleteResponse *clientv3.DeleteResponse
err error
)
ctx, cancelFunc = context.WithTimeout(ctx, timeout)
defer cancelFunc()
if deleteResponse, err = Client.Delete(ctx, key, optionList...); nil != err {
return nil, errors.New("delete key fail : " + err.Error())
}
return deleteResponse, nil
}
// DeleteWithKeyPrefix 基于 key 前缀, 删除key
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2:12 下午 2021/11/24
func DeleteWithKeyPrefix(ctx context.Context, keyPrefix string, timeout time.Duration) (*clientv3.DeleteResponse, error) {
return DeleteWithOption(ctx, keyPrefix, timeout, clientv3.WithPrefix())
}

View File

@ -0,0 +1,22 @@
// Package etcd...
//
// Description : etcd...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-11-24 2:11 下午
package etcd
import (
"fmt"
"testing"
)
// TestDeleteWithKeyPrefix ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2:11 下午 2021/11/24
func TestDeleteWithKeyPrefix(t *testing.T) {
fmt.Println(DeleteWithKeyPrefix(nil, "/test", 0))
}