etcd #4

Merged
zhangdeman merged 7 commits from feature/etcd into master 2021-11-23 16:55:58 +08:00
2 changed files with 76 additions and 0 deletions
Showing only changes of commit 0898107e92 - Show all commits

View File

@ -12,6 +12,7 @@ import (
"time" "time"
) )
// 初始化client各种默认配置
const ( const (
// DefaultDialTimeout 默认超时时间 // DefaultDialTimeout 默认超时时间
DefaultDialTimeout = 5 * time.Second DefaultDialTimeout = 5 * time.Second
@ -24,3 +25,11 @@ const (
// DefaultMaxCallRecvMsgSize 客户端接受的响应题最大大小, 默认int32最大值, 和etcd默认值保持一致 // DefaultMaxCallRecvMsgSize 客户端接受的响应题最大大小, 默认int32最大值, 和etcd默认值保持一致
DefaultMaxCallRecvMsgSize = math.MaxInt32 DefaultMaxCallRecvMsgSize = math.MaxInt32
) )
// 操作过程中各种默认配置
const (
// DefaultPutTimeout put 默认超时时间
DefaultPutTimeout = time.Second
// DefaultGetTimeout get 默认超时时间
DefaultGetTimeout = time.Second
)

67
middleware/etcd/string.go Normal file
View File

@ -0,0 +1,67 @@
// Package etcd...
//
// Description : etcd...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-11-23 12:09 下午
package etcd
import (
"context"
"time"
"github.com/coreos/etcd/mvcc/mvccpb"
"go.etcd.io/etcd/clientv3"
)
// Put put数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:09 下午 2021/11/23
func Put(ctx context.Context, key string, val string, operateTimeout time.Duration) error {
if operateTimeout <= 0 {
operateTimeout = DefaultPutTimeout
}
var (
cancel context.CancelFunc
err error
)
if nil == ctx {
ctx = context.Background()
}
ctx, cancel = context.WithTimeout(ctx, operateTimeout)
_, err = Client.Put(ctx, key, val)
cancel()
return err
}
// Get 读取数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:09 下午 2021/11/23
func Get(ctx context.Context, key string, operateTimeout time.Duration) (
[]*mvccpb.KeyValue,
error,
) {
if operateTimeout <= 0 {
operateTimeout = DefaultGetTimeout
}
var (
cancel context.CancelFunc
err error
result *clientv3.GetResponse
)
if nil == ctx {
ctx = context.Background()
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
result, err = Client.Get(ctx, key)
cancel()
if err != nil {
return nil, err
}
return result.Kvs, nil
}