当前位置:网站首页>【锁】Redis锁 处理并发 原子性
【锁】Redis锁 处理并发 原子性
2022-07-01 14:53:00 【我是Superman丶】
【锁】Redis锁 处理并发 原子性
如果为空就set值,并返回1
如果存在(不为空)不进行操作,并返回0
很明显,比get和set要好。因为先判断get,再set的用法,有可能会重复set值。
setIfAbsent 和 setnx
setIfAbsent 是java中的方法
setnx 是 redis命令中的方法
说明:当key不存在,将key的值设为value,并设置过期时间,返回true;若给定的key已经存在,则不做任何动作,并返回false。此方法是原子性的
@Autowired
private RedisTemplate redisTemplate;
/**
* 加锁
* @param key key
* @param value value
* @param timeout 过期时间单位秒
* @param false表示有锁 / true表示key不存在 无锁
*/
public boolean getLock(String key, String value, long timeout) {
try {
//原子性操作
boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
//如果存在false表示重复
return flag;
} catch (Exception e) {
logger.error("redis加锁异常", e);
//出现异常删除锁
redisTemplate.delete(key);
return true;
}
}redis命令
redis> SETNX mykey "Hello"
(integer) 1
redis> SETNX mykey "World"
(integer) 0
redis> GET mykey
"Hello"
边栏推荐
- 使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器
- Tensorflow 2. X realizes iris classification
- Semiconductor foundation of binary realization principle
- [getting started with Django] 13 page Association MySQL "multi" field table (check)
- 职场太老实,总被欺负怎么办?
- Error-tf. function-decorated function tried to create variables on non-first call
- After twists and turns, I finally found the method of SRC vulnerability mining [recommended collection]
- NPDP产品经理国际认证报名有什么要求?
- Opencv mat class
- tensorflow2-savedmodel convert to tflite
猜你喜欢

JVM performance tuning and practical basic theory part II

JVM第二话 -- JVM内存模型以及垃圾回收

Leetcode (69) -- square root of X

Guess lantern riddles, not programmers still can't understand?

MIT团队使用图神经网络,加速无定形聚合物电解质筛选,促进下一代锂电池技术开发
![[leetcode 324] 摆动排序 II 思维+排序](/img/cb/26d89e1a1f548b75a5ef9f29eebeee.png)
[leetcode 324] 摆动排序 II 思维+排序

Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models

Basic operations of SQL database

Sqlachemy common operations

Internet hospital system source code hospital applet source code smart hospital source code online consultation system source code
随机推荐
sqlilabs less10
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
Storage form of in-depth analysis data in memory
Develop small programs and official account from zero [phase III]
炎炎夏日,这份安全用气指南请街坊们收好!
Apk signature principle
基于价值量化的需求优先级排序方法
首届技术播客月开播在即
What are the books that have greatly improved the thinking and ability of programming?
241. Design priorities for operational expressions
MongoDB第二话 -- MongoDB高可用集群实现
2022-2-15 learning xiangniuke project - Section 1 filtering sensitive words
JVM second conversation -- JVM memory model and garbage collection
网速、宽带、带宽、流量三者之间的关系是什么?
Music player development example (can be set up)
[15. Interval consolidation]
[stage life summary] I gave up the postgraduate entrance examination and participated in the work. I have successfully graduated and just received my graduation certificate yesterday
TypeScript:const
APK签名原理
Markdown编辑器使用基本语法