当前位置:网站首页>How to encapsulate distributed locks more elegantly
How to encapsulate distributed locks more elegantly
2020-11-06 01:19:51 【Yin Jihuan】
Distributed locks usually have many choices , be based on Redis Of , be based on Zookeeper Of , Based on database and so on .
Redis For caching data , It's used in projects , So use Redis There will be a little more distributed locks .
If you use Redis To make a lock , You can use open source solutions directly , such as redisson.
The most common uses are as follows :
RLock lock = redisson.getLock("anyLock");
lock.lock();
run();
lock.unlock();
Get lock object , call lock() Lock , Execute business logic , call unlock() Release the lock .
Although the framework provides a very simple way to use it , But we still need to do a layer of packaging for the lock . The purpose of packaging is to improve scalability and ease of use .
Abstract interface
If we use it directly redisson The native API Make locks , So many places will appear RLock Related code , And then one day , For some reason , The lock needs to be replaced , At this time, the scope of change is relatively large . Each uses RLock Everything has to be changed .
Here's the picture : quite a lot Service Are used to RLock.lock() Method , When we need to replace locks , All the classes and methods involved have to be modified , The change points are shown in the red section .
So we need to do a layer of abstraction , You can define a DistributedLock Interface to provide lock related capabilities , Provides multiple implementations , This makes it easy to replace and expand .
Here's the picture : Every Service It's all for DistributedLock Interface to lock , When we need to replace the lock implementation , It doesn't need to be changed , Just replace DistributedLock The realization of .
Automatic release
Automatic release refers to after locking , After the execution of business logic, the lock needs to be closed automatically . In front of Redisson We need to manually call unlock() To release the lock held .
Of course Redisson It also provides the function of timeout release , Under normal circumstances, the lock must be released after the completion of business execution , The next request for the same lock can continue to be processed .
The most common problem with manually releasing resources is forgetting to release , So in JDK7 Introduced in try-with-resources To release resources automatically , I believe everyone is familiar with .
So when we encapsulate , Try not to let the user release it manually , Reduce the probability of error . For those with results, we can use Supplier To deliver your logic , For those that do not return results, you can use Runnable To deliver your logic .
/**
* Lock
* @param key lock Key
* @param waitTime Try to lock , Waiting time (ms)
* @param leaseTime Failure time after locking (ms)
* @param success The logic of successful lock execution
* @param fail Logic of lock failure execution
* @return
*/
<T> T lock(String key, int waitTime, int leaseTime, Supplier<T> success, Supplier<T> fail);
Use :
String result = distributedLock.lock("1001", 1000, () -> {
System.out.println(" Came in ....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "success";
}, () -> {
System.out.println(" Locking failed ....");
return "fail";
});
Disaster recovery
Another issue to note is the availability of locks , In case the corresponding Redis Something is wrong. , This time to lock is bound to fail , If nothing is done , It will affect normal business operations , Make the business unavailable .
In addition to realizing Redis Outside the lock of , Other locks can be implemented , Like database locks . When Redis When a lock is not available, it is demoted to a database lock , Although performance has an impact , But it doesn't affect the business .
If the database lock is not available ( Digression : It's very unlikely that everything will be available ), It's better to let business operations fail . Because we use the lock scene , It must be to prevent problems caused by concurrent scenarios , If the lock is not available , You're going to spend abnormally , Let business operations continue , There may be business problems without locking .
Of course, monitoring is also very necessary ,Redis, Database monitoring . When something goes wrong , There's a timely intervention .
Monitoring system
Redis, database ,Zookeeper The monitoring of these middleware supporting distributed implementation is definitely necessary . Another monitoring is the fine-grained monitoring of the lock action .
For example, the time to lock , Time to release lock , Time to execute business in a lock , Lock concurrency , Number of executions , The number of lock failures .
These data indicators are very important , It can help you find problems in time . such as 10 Hundreds of lock failures per second , All demoted to database locks , This is when you get an alert , It's easy to see Redis Something is wrong. , Timely solution .
The way of monitoring is just as casual , Every company is different , You can expose data to Prometheus Grab , You can also integrate Cat Do a good job , As long as you can monitor , Just give an alarm .
About author : Yin Jihuan , Simple technology enthusiasts ,《Spring Cloud Microservices - Full stack technology and case analysis 》, 《Spring Cloud Microservices introduction Actual combat and advanced 》 author , official account Ape world Originator .
I have compiled a complete set of learning materials , Those who are interested can search through wechat 「 Ape world 」, Reply key 「 Learning materials 」 Get what I've sorted out Spring Cloud,Spring Cloud Alibaba,Sharding-JDBC Sub database and sub table , Task scheduling framework XXL-JOB,MongoDB, Reptiles and other related information .
版权声明
本文为[Yin Jihuan]所创,转载请带上原文链接,感谢
边栏推荐
- C++ 数字、string和char*的转换
- C++学习——centos7上部署C++开发环境
- C++学习——一步步学会写Makefile
- C++学习——临时对象的产生与优化
- C++学习——对象的引用的用法
- C++编程经验(6):使用C++风格的类型转换
- Won the CKA + CKS certificate with the highest gold content in kubernetes in 31 days!
- C + + number, string and char * conversion
- C + + Learning -- capacity() and resize() in C + +
- C + + Learning -- about code performance optimization
猜你喜欢
-
C + + programming experience (6): using C + + style type conversion
-
Latest party and government work report ppt - Park ppt
-
在线身份证号码提取生日工具
-
Online ID number extraction birthday tool
-
️野指针?悬空指针?️ 一文带你搞懂!
-
Field pointer? Dangling pointer? This article will help you understand!
-
HCNA Routing&Switching之GVRP
-
GVRP of hcna Routing & Switching
-
Seq2Seq实现闲聊机器人
-
【闲聊机器人】seq2seq模型的原理
随机推荐
- LeetCode 91. 解码方法
- Seq2seq implements chat robot
- [chat robot] principle of seq2seq model
- Leetcode 91. Decoding method
- HCNA Routing&Switching之GVRP
- GVRP of hcna Routing & Switching
- HDU7016 Random Walk 2
- [Code+#1]Yazid 的新生舞会
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- HDU7016 Random Walk 2
- [code + 1] Yazid's freshman ball
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- Qt Creator 自动补齐变慢的解决
- HALCON 20.11:如何处理标定助手品质问题
- HALCON 20.11:标定助手使用注意事项
- Solution of QT creator's automatic replenishment slowing down
- Halcon 20.11: how to deal with the quality problem of calibration assistant
- Halcon 20.11: precautions for use of calibration assistant
- “十大科学技术问题”揭晓!|青年科学家50²论坛
- "Top ten scientific and technological issues" announced| Young scientists 50 ² forum
- 求反转链表
- Reverse linked list
- js的数据类型
- JS data type
- 记一次文件读写遇到的bug
- Remember the bug encountered in reading and writing a file
- 单例模式
- Singleton mode
- 在这个 N 多编程语言争霸的世界,C++ 究竟还有没有未来?
- In this world of N programming languages, is there a future for C + +?
- es6模板字符
- js Promise
- js 数组方法 回顾
- ES6 template characters
- js Promise
- JS array method review
- 【Golang】️走进 Go 语言️ 第一课 Hello World
- [golang] go into go language lesson 1 Hello World