diff --git a/middleware/etcd/define.go b/middleware/etcd/define.go index 630176e..d2b3f59 100644 --- a/middleware/etcd/define.go +++ b/middleware/etcd/define.go @@ -34,6 +34,8 @@ const ( DefaultPutTimeout = time.Second // DefaultGetTimeout get 默认超时时间 DefaultGetTimeout = time.Second + // DefaultDeleteTimeout 删除的超时时间 + DefaultDeleteTimeout = time.Second ) // WatcherHandler 监听key变化的处理函数 diff --git a/middleware/etcd/delete.go b/middleware/etcd/delete.go new file mode 100644 index 0000000..0a62445 --- /dev/null +++ b/middleware/etcd/delete.go @@ -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()) +} diff --git a/middleware/etcd/delete_test.go b/middleware/etcd/delete_test.go new file mode 100644 index 0000000..dbcbf49 --- /dev/null +++ b/middleware/etcd/delete_test.go @@ -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)) +}