当前位置:网站首页>【锁】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"
边栏推荐
- Generate random numbers (4-bit, 6-bit)
- 一波三折,终于找到src漏洞挖掘的方法了【建议收藏】
- Advanced C language
- What data capabilities do data product managers need to master?
- Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models
- tensorflow2-savedmodel convert to pb(frozen_graph)
- Yyds dry goods inventory hcie security day13: firewall dual machine hot standby experiment (I) firewall direct deployment, uplink and downlink connection switches
- 【14. 区间和(离散化)】
- Guess lantern riddles, not programmers still can't understand?
- tensorflow2-savedmodel convert to tflite
猜你喜欢

SQLAchemy 常用操作

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

C learning notes (5) class and inheritance

【14. 区间和(离散化)】

Vnctf2022 open web gocalc0

定了!2022海南二级造价工程师考试时间确定!报名通道已开启!

Opencv interpolation mode

Minimum spanning tree and bipartite graph in graph theory (acwing template)

Yyds dry goods inventory hcie security day13: firewall dual machine hot standby experiment (I) firewall direct deployment, uplink and downlink connection switches

竣达技术丨多台精密空调微信云监控方案
随机推荐
定了!2022海南二级造价工程师考试时间确定!报名通道已开启!
首届技术播客月开播在即
一波三折,终于找到src漏洞挖掘的方法了【建议收藏】
MongoDB第二话 -- MongoDB高可用集群实现
What data capabilities do data product managers need to master?
TypeScript:const
What are the books that have greatly improved the thinking and ability of programming?
643. Maximum average number of subarrays I
C learning notes (5) class and inheritance
[零基础学IoT Pwn] 复现Netgear WNAP320 RCE
One of the data Lake series | you must love to read the history of minimalist data platforms, from data warehouse, data lake to Lake warehouse
Day-02 database
solidty-基础篇-结构体和数组,私有 / 公共函数,函数的返回值和修饰符,事件
三十之前一定要明白的职场潜规则
Develop small programs and official account from zero [phase III]
QT capture interface is displayed as picture or label
tensorflow2-savedmodel convert to pb(frozen_graph)
One of the first steps to redis
Don't want to knock the code? Here comes the chance
【14. 区间和(离散化)】