Etcd源码分析之clientv3源码分析(2)
在上一篇博客《Etcd源码分析之clientv3源码分析(1)》中介绍了如何创建一个clientv3的流程,在本篇博客中以一个PUT操作为例,介绍一下PUT、GET和DELETE这三个键值相关操作中的代码流程。
PUT操作样例程序
首先,一个简单的PUT操作代码代码样例如下:
import (
"context"
"log"
"time"
"github.com/coreos/etcd/clientv3"
)
var (
dialTimeout = 5 * time.Second
requestTimeout = 10 * time.Second
endpoints = []string{
"localhost:2379"}
)
//此函数来源于 -->etcd-3.3.1/clientv3/example_kv_test.go line:26
func ExampleKV_put() {
//创建一个客户端
cli, err := clientv3.New(clientv3.Config{
Endpoints: endpoints , //客户端了解到服务端的localhost:2379
DialTimeout: dialTimeout, //grpc 连接建立超时时间为5s
})
if err != nil {
log.Fatal(err)
}
//函数退出前关闭客户端
defer cli.Close()
//因为clientv3里面设置了重试机制,如果一个endpoint不可用,clientv3会尝试其他endpoint,即使所有的
//endpoints都不可用,如果不配置ctx为WithTimeout类型,clientV3会一直在重试,直到有可用endpoint,
//将Put请求发送出去为止。所以此处配置了requestTimeout(10s),10s内Put操作还没有完成,则取消该操作,
//同时Put也会返回错误。
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
_, err = cli.Put(ctx, "sample_key", "sample_value") //PUT sample_key sample_value
cancel() //虽然10s之后,ctx会自动失效,但是这里还是执行以下cancel()函数,避免context泄露。
if err != nil {
log.Fatal(err)
}
}
func main(){
ExampleKV_put()
}
PUT操作源码分析
对于Put操作,执行的是Client结构体中的Put函数,该函数属于KV interface
// 原代码见-->etcd-3.3.1/clientv3/kv.go line:33
type KV interface {
// Put puts a key-value pair into etcd.
// Note that key,value can be plain bytes array and string is
// an immutable representation of that bytes array.
// To get a string of bytes, do string([]byte(0x10, 0x20)).
Put(ctx context.Context, key, val string, opts ...OpOption) (*PutResponse, error)
// Get retrieves keys.
// By default, Get will return the value for &