当前位置:网站首页>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;
}
}
边栏推荐
- CSDN recommended template
- Google Earth engine -- a small bug in gee. Images of transcontinental boundaries cannot be obtained
- [ardunio] two methods to control the steering gear
- Is it risky and safe to open an account?
- 容器网络原理
- 解决报错:Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “
- Okaleido tiger NFT即将登录Binance NFT平台,你期待吗?
- script之type=module
- Creo 9.0 中几何对象的选取方法
- 赛扬n5095处理器怎么样 英特尔n5095核显相当于什么水平
猜你喜欢

rtx3080ti和rtx3080差距 3080和3080ti参数对比

MYSQL练习题:向CEO汇报的所有员工

第十一天笔记

Creo 9.0 中几何对象的选取方法

LeetCode_ 52_ Queen n II

These five points should be considered in the production of enterprise science and technology exhibition hall

Creo 9.0 如何快速修改CAD坐標系?

Static comprehensive experiment (HCIA)

BERT 文章翻译

LeetCode_ 51_ Queen n
随机推荐
Google Earth Engine——gee中的小bug跨洲边际的影像无法获取
京东云分布式链路追踪在金融场景的最佳实践
Redis常用命令
网络安全笔记1——Internet协议的安全性
T-SEDA编码
Golang remote server debugging
Network security note 1 - Security of Internet Protocol
酷睿i5 12490f和i5 12600k差距大吗
Image processing 6: top level file
Head products generated 2.5 billion yuan, and SLG track was also targeted by black products
GRE,MGRE的詳細了解;OSPF基礎配置知識
golang远程服务器调试
Notes on key vocabulary of the original English book biography of jobs (15) [chapter four]
Ansible first knowledge of learning one
数千个数据库、遍布全国的物理机,京东物流全量上云实录 | 卓越技术团队访谈录
Kotlin - suspend function
天玑820相当于骁龙多少处理器 天玑1100相当于骁龙多少 天玑820怎么样
CSDN recommended template
考研题库小程序中如何实现打开考研思维导图pdf
Événements courants de la souris et du clavier