当前位置:网站首页>Learn how to implement distributed locks in redis - my own understanding
Learn how to implement distributed locks in redis - my own understanding
2022-06-30 11:43:00 【Full stack programmer webmaster】
One 、 Import maven rely on <!– operation redis Of java client jedis –> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> Two 、 Code implementation import java.util.UUID;
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool;
/** * The idea of distributed locking : Multiple server clusters , Only one of them is allowed jvm To operate * redis The idea of implementing distributed lock : * * Get the lock : In more than one jvm Under the circumstances ,redis Realize distributed lock passing setnx Method to create the same key , * This key Is the only one that does not repeat , If the deposit is successful, return 1 Get the lock , Failure to deposit returns 0,value Use a unique non repeating random number as the thread's ID. * * Release the lock : In order to guarantee the lock acquired by the thread , The lock released is the same , In the delete reids Of key When , To ID Judge , Is the same ID Before deleting * * How to prevent deadlock * 1. Set a time period before acquiring a lock , If the thread has not acquired the lock in this time period , Then the thread will give up acquiring the lock , return null * 2. Also set another time period , After the thread obtains the lock , Yes key Set the effective time , After this is the time period ,key Automatically delete , Release the lock Return thread ID * * @author zxlovey * */ public class LockRedis { // jedis Thread pool private JedisPool jedisPool;
public LockRedis(JedisPool jedisPool) { this.jedisPool = jedisPool; }
private String reidsKey = “redis_key”;
// Get the lock /** * * @param acquireTimeout * A period of time before a lock is acquired * @param timeOut * After the thread gets the lock , Yes key Set the effective time Usually in seconds */ public String getLockRedis(Long acquireTimeout, Long timeOut) { Jedis conn = null; try { // Get jedis conn = jedisPool.getResource();
Long endTime = System.currentTimeMillis() + acquireTimeout; int expireLock = (int) (timeOut / 1000);
String identifierValue = UUID.randomUUID().toString();
while (System.currentTimeMillis() < endTime) { if (conn.setnx(reidsKey, identifierValue) == 1) { // Get the lock Set the effective time conn.expire(reidsKey, expireLock); // return value, This value As thread id When releasing the lock, you need to judge the deleted key It is the same as the acquired lock return identifierValue; } }
} catch (Exception e) { // TODO: handle exception } finally { if (conn != null) { conn.close(); } }
return null; }
// Release the lock /** * * @param identifierValue * The lock ID, Namely key Corresponding value */ public void unLockRedis(String identifierValue) { Jedis conn = null; try { conn = jedisPool.getResource();
if (conn.get(reidsKey).equals(identifierValue)) { // Acquired key Of value identical , Description is the lock resource of the same thread // Delete key conn.del(reidsKey); System.out.println(“ Lock release successful :” + Thread.currentThread().getName() + “— The lock ID:” + identifierValue); }
} catch (Exception e) {
} finally { if (conn != null) { conn.close(); } } }
}
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig;
public class LockServer { private static JedisPool pool = null;
static { JedisPoolConfig config = new JedisPoolConfig(); // Set the maximum number of connections config.setMaxTotal(200); // Set the maximum number of idle config.setMaxIdle(8); // Set the maximum waiting time config.setMaxWaitMillis(1000 * 100); // stay borrow One jedis When an instance , Is it necessary to verify , if true, Then all jedis Instances are available config.setTestOnBorrow(true); pool = new JedisPool(config, “127.0.0.1”, 6379, 3000); } private LockRedis lockRedis = new LockRedis(pool); // demonstration redis Implement distributed locks public void seckill() { //1. Get lock String identifierValue = lockRedis.getLockRedis(1000L, 1000L); if(identifierValue == null){ System.out.println(“ Lock acquisition failed :”+Thread.currentThread().getName()+”; The reason for the failure is that the time to acquire the lock timed out ”); return; } System.out.println(“ Lock acquired successfully :”+Thread.currentThread().getName()+”— The lock ID:”+identifierValue); //2. Release the lock lockRedis.unLockRedis(identifierValue); } }
public class ThreadLock extends Thread{ private LockServer lockServer; public ThreadLock(LockServer lockServer) { this.lockServer = lockServer; } @Override public void run() { lockServer.seckill(); } }
public class Test001 { public static void main(String[] args) { LockServer lockServer = new LockServer(); for (int i = 0; i < 500; i++) { ThreadLock tl = new ThreadLock(lockServer); tl.start(); } } }
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/100803.html Link to the original text :https://javaforall.cn
边栏推荐
- Filter error in dplyr: can't transform a data frame with duplicate names
- STM32F407ZGT6使用SDIO方式驱动SD卡
- Le talent scientifique 丨 dessins animés qu'est - ce qu'erdma?
- A man is a Book
- 基于视觉的机器人抓取:从物体定位、物体姿态估计到平行抓取器抓取估计
- 考研这些“不靠谱”的经验有多害人?
- Typescript readonlyarray (read only array type) details
- Esp32-c3 introductory tutorial basic part ⑫ - mass production burning device configuration and serial number, NVS partition confirmation, NVS partition generation program, CSV to bin
- The latest collection of arouter problems
- Uncover the whole link communication process of customer service im
猜你喜欢

Database connection pool Druid

Handler source code analysis

What is erdma as illustrated by Coptic cartoon?
![[xi'anjiaotonguniversity] information sharing of the first and second postgraduate entrance examinations](/img/06/df5a64441814c9ecfa2f039318496e.jpg)
[xi'anjiaotonguniversity] information sharing of the first and second postgraduate entrance examinations

“新数科技”完成数千万元A+轮融资,造一体化智能数据库云管理平台

以PolarDB为代表的阿里云数据库以跻身全球第一阵营

"War" caused by a bottle of water

国产数据库的黄金周期要来了吗?

导致系统性能失败的10个原因

他是上海两大产业的第一功臣,却在遗憾中默默离世
随机推荐
PointDistiller:面向高效紧凑3D检测的结构化知识蒸馏
100 important knowledge points that SQL must master: summary data
R语言去重操作unique duplicate filter
数学(快速幂)
1175. prime permutation
Esp32-c3 introductory tutorial IOT part ⑤ - Alibaba cloud Internet of things platform espaliyun RGB LED practical mass production solution
win10 R包安装报错:没有安装在arch=i386
ARouter 最新问题合集
Shutter from zero 004 button assembly
Flutter start from scratch 008 form
达梦数据冲刺科创板,或成A股市场“国产数据库第一股”
19年来最艰难的618,徐雷表达三个谢意
ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528
微信表情符号被写入判决书,你发的每个 emoji 都可能成为呈堂证供
Dameng data rushes to the scientific innovation board, or becomes the "first share of domestic database" in the A-share market
Line generation (Gauss elimination method, linear basis)
Kotlin 协程调度切换线程是时候解开谜团了
Train an image classifier demo in pytorch [learning notes]
QT embeds the sub QT program window into the current program
一个人就是一本书