当前位置:网站首页>Using redis to realize distributed lock (single redis)
Using redis to realize distributed lock (single redis)
2022-07-23 14:05:00 【Brother Yu...】
because redis It's a single threaded program , It can naturally ensure thread safety , As long as our order is a single order , It can ensure the safety of operation , and redis Provided in setnx key value command , Said when redis There is no key The key value of , Will create the value of this key value pair , If there are already , It doesn't work ,java There is valueOperations.setIfAbsent(key,value) And redis Medium setnx It's the same thing . We can use valueOperations.setIfAbsent Realize the operation of distributed locking , You can also set the expiration time for the lock , In this way, even if the client fails, the lock can be released after the expiration time
Boolean isLock=valueOperations.setIfAbsent("k1",value,120,TimeUnit.SECONDS);
key It's any value ,value Ensure the uniqueness of each user , Easy to release the lock , Because we are releasing the lock, that is del key when , It needs to be ensured that only the program that actually obtains the lock can release the corresponding lock , Not everyone can release the lock , Prevent yourself from getting locked and being released by others , So the step of releasing the lock is :
- First judge the value of the lock variable , Whether you got the lock yourself
- If the lock is obtained by yourself , You can release the lock
- If you don't get the lock yourself , The lock cannot be released
This is not an order , But we need these commands to be executed atomically , So we use lua Script .Redis Yes lua Script calls are atomic , So some special scenes , Can be placed in lua To realize , Here is a simple example
First, in the resources Create one in the directory lock.lua file
if redis.call("get",KEYS[1])==ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end
When you type key[1] stay redis Is equal to the entered argv[1] when , Delete the original key, Release the lock , The lock cannot be released without waiting key[1]: Entered when acquiring the lock key,argv[1]: Entered when acquiring the lock value
@Test
public void testLock03() {
ValueOperations valueOperations=redisTemplate.opsForValue();
String value= UUID.randomUUID().toString();
// If key It's empty , Just set the value
Boolean isLock=valueOperations.setIfAbsent("k1",value,120,TimeUnit.SECONDS);
if(isLock) {
valueOperations.set("name","xxxx");
String name=(String)valueOperations.get("name");
System.out.println("name="+name);
System.out.println(valueOperations.get("k1"));
Boolean result=(Boolean)redisTemplate.execute(script, Collections.singletonList("k1"),value);
System.out.println(result);
}
else {
System.out.println(" There are threads in use , Please later ");
}
}
among singletonList Is an immutable list, And only one element , It's from redis take k1 Corresponding value, Look and method passed in value Same, different , The same thing is direct key( Release the lock ).
redisConfig class
// Serialize information , stay redis It looks good in
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//key Serialization
redisTemplate.setKeySerializer(new StringRedisSerializer());
//value Serialization
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//hash type key Serialization
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//hash type value Serialization
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
// Injection connection factory
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
@Bean
public DefaultRedisScript<Boolean> script() {
DefaultRedisScript<Boolean> redisScript=new DefaultRedisScript<>();
redisScript.setLocation(new ClassPathResource("lock.lua"));
redisScript.setResultType(Boolean.class);
return redisScript;
}
}
边栏推荐
- C: readonly and Const
- 天玑1100相当于骁龙多少处理器 天玑1100相当于骁龙多少 天玑1100怎么样
- What's the difference between core i9 12950hx and i9 12900hx
- 图像处理4:腐蚀
- 腾讯MMKV的原理与实现
- OSPF详解(LSA)(2)
- Detailed understanding of GRE and mGRE; OSPF basic configuration knowledge
- 图像处理7:测试文件
- 图像处理1:RGB888_YCbCr444
- Matlab: convert PNG pictures into txt files
猜你喜欢
随机推荐
Kingbasees formatting function
The fourth operation
Événements courants de la souris et du clavier
LeetCode_ 46_ Full Permutation
BERT 文章翻译
In depth analysis of common cross end technology stacks of app
How to ensure the reliable transmission of messages? What if the message is lost
记一次Vulnhub靶机练习成功拿下root权限
[机缘参悟-50]:鬼谷子-第十二符言篇-当好领导者的艺术:守其位,观四方,洞危险,广言路,虚谏言,定规则,明赏罚,符名实,得民心。
What's the difference between core i9 12950hx and i9 12900hx
Color recognition of regions of interest in pictures and videos based on OpenCV
Life essays: annoying projects in 2022
golang远程服务器调试
Google Earth engine -- a small bug in gee. Images of transcontinental boundaries cannot be obtained
C #: in, out, ref Keywords
script之type=module
rip的详细介绍
LeetCode_ 2342_ Maximum sum of digits and equal pairs
第十一天笔记
Xilinx FPGA一路时钟输入两个PLL








