当前位置:网站首页>Etcd tutorial - Chapter 9 etcd implementation of distributed locks
Etcd tutorial - Chapter 9 etcd implementation of distributed locks
2022-06-30 16:50:00 【Ximu Qi】
Etcd course — Chapter nine Etcd Implementation of distributed lock
One 、 adopt Etcd txn Implement distributed locks
adopt Etcd Implement distributed locks , It also needs to be consistent 、 Mutual exclusion and reliability .Etcd The transaction txn、lease The lease and watch Monitoring features , Can make based on Etcd Distributed locks that implement the above requirements .
1.1 Thought analysis
adopt Etcd The transaction features of can help us achieve consistency and mutual exclusion .Etcd The transactional nature of , The use of IF-Then-Else sentence ,IF Language judgment Etcd Whether the server has the specified key, That is, the key Create version number create_revision Is it 0 To check key Does it already exist , Because it's time to key If it already exists , its create_revision The version number is not 0.
Satisfy IF In the case of condition, use then perform put operation , otherwise else Statement returns the result of the failed lock snatch . Of course , Besides using key Whether it was successfully created as IF On the basis of , You can also create... With the same prefix key, Compare these key Of revision To determine which request the distributed lock should belong to .
The client requests that after getting the distributed lock , If something unusual happens , The lock needs to be released in time . So you need a lease , When we apply for distributed locks, we need to specify the lease time . exceed lease The lease time will automatically release the lock , Ensure the availability of the business .
Is that enough ? When executing business logic , If the client initiates a time-consuming operation , If the operation is not completed, please , The lease has expired , Causes other requests to acquire distributed locks , To cause disagreement . In this case, it needs to be renewed , That is to refresh the lease , Enables the client to communicate with etcd The server keeps the heartbeat .
Two 、 Concrete realization
2.1 flow chart
We are based on the above analysis , Draw the implementation etcd Flow chart of distributed lock , As shown below :
2.2 Implementation code
be based on Go The realization of language etcd Distributed lock , The test code is as follows :
func TestLock(t *testing.T) {
// Client configuration
config = clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
}
// Establishing a connection
if client, err = clientv3.New(config); err != nil {
fmt.Println(err)
return
}
// 1. Lock and create a lease
lease = clientv3.NewLease(client)
if leaseGrantResp, err = lease.Grant(context.TODO(), 5); err != nil {
panic(err)
}
leaseId = leaseGrantResp.ID
// 2 Automatic renewal
// Create a cancellable lease , The main purpose is to release when you exit
ctx, cancelFunc = context.WithCancel(context.TODO())
// 3. Release the lease
defer cancelFunc()
defer lease.Revoke(context.TODO(), leaseId)
if keepRespChan, err = lease.KeepAlive(ctx, leaseId); err != nil {
panic(err)
}
// Renewal response
go func() {
for {
select {
case keepResp = <-keepRespChan:
if keepRespChan == nil {
fmt.Println(" The lease has lapsed ")
goto END
} else { // It will be renewed every second , So you get a response
fmt.Println(" Auto renewal response received :", keepResp.ID)
}
}
}
END:
}()
// 1.3 Grab the lock during the lease time (etcd The lock inside is one key)
kv = clientv3.NewKV(client)
// Create transaction
txn = kv.Txn(context.TODO())
//if non-existent key,then Set it up ,else Lock snatch failed
txn.If(clientv3.Compare(clientv3.CreateRevision("lock"), "=", 0)).
Then(clientv3.OpPut("lock", "g", clientv3.WithLease(leaseId))).
Else(clientv3.OpGet("lock"))
// Commit transaction
if txnResp, err = txn.Commit(); err != nil {
panic(err)
}
if !txnResp.Succeeded {
fmt.Println(" Lock occupied :", string(txnResp.Responses[0].GetResponseRange().Kvs[0].Value))
return
}
// After seizing the lock, execute the business logic , There's no exit
fmt.Println(" Processing tasks ")
time.Sleep(5 * time.Second)
}
The expected implementation results are as follows :
=== RUN TestLock
Processing tasks
Auto renewal response received : 7587848943239472601
Auto renewal response received : 7587848943239472601
Auto renewal response received : 7587848943239472601
--- PASS: TestLock (5.10s)
PASS
In general , As mentioned above about etcd The implementation process of distributed lock is divided into four steps :
- Client initialization and connection establishment ;
- Create a lease , Automatic renewal ;
- Create transaction , Get the lock ;
- Execute business logic , Finally release the lock .
When you create a lease , You need to create a cancellable lease , The main purpose is to release when you exit . The steps to release the lock , Above defer In the sentence . When defer When the lease closes , Distributed locks correspond to key Will be released .
边栏推荐
- 数据挖掘知识点整理(期末复习版)
- MySQL8.0开启远程连接权限的方法步骤
- Hologres shared cluster helps Taobao subscribe to the extreme refined operation
- 招标公告:天津市住房公积金管理中心数据库一体机及数据库软件项目(预算645万)
- Talk about telecommuting | community essay solicitation
- Under the pressure of technology, you can quickly get started with eth smart contract development, which will take you into the ETH world
- Li Zexiang, a legendary Chinese professor, is making unicorns in batches
- Mathematical modeling for war preparation 34-bp neural network prediction 2
- register_chrdev和cdev_init cdev_add用法区别
- 2020 Blue Bridge Cup group B - move bricks - (greedy sorting +01 backpack)
猜你喜欢

JS Es5 can also create constants?
![[machine learning] K-means clustering analysis](/img/5f/3199fbd4ff2129d3e4ea518812c9e9.png)
[machine learning] K-means clustering analysis

Etcd教程 — 第八章 Etcd之Compact、Watch和Lease API
![Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]](/img/e2/cadfdbe476a86cb2d72c1ae0160a4a.png)
Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]

Symantec electronic sprint technology innovation board: Tan Jian, the actual controller, is an American who plans to raise 620million yuan
![[Verilog quick start of Niuke online question series] ~ bit splitting and operation](/img/17/4b8f5607c4cba1596435233a6cf30a.png)
[Verilog quick start of Niuke online question series] ~ bit splitting and operation

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

RT thread heap size setting

中国传奇教授李泽湘,正在批量制造独角兽

Mathematical modeling for war preparation 33- grey prediction model 2
随机推荐
深度学习——(2)几种常见的损失函数
IndexSearch
Raft介绍
安全帽佩戴检测算法研究
数据挖掘知识点整理(期末复习版)
jspreadsheet/CE JExcel数据字段比给的字段(columns)多会导致空白列的问题解决方案
dart:字符串replace相关的方法解决替换字符
CVPR 2022 - Tesla AI proposed: generalized pedestrian re recognition based on graph sampling depth metric learning
9:第三章:电商工程分析:4:【通用模块】;(待写……)
备战数学建模33-灰色预测模型2
Hologres共享集群助力淘宝订阅极致精细化运营
register_ Chrdev and CDEV_ init cdev_ Add usage differences
Halcon knowledge: matrix topic [02]
[Verilog basics] octal and hexadecimal representation of decimal negative numbers
Half year inventory of new consumption in 2022: the industry is cold, but these nine tracks still attract gold
华为帐号多端协同,打造美好互联生活
Niuke network: longest continuous subarray with positive product
15年做糊21款硬件,谷歌到底栽在哪儿?
【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
RTP sending PS stream zero copy scheme