当前位置:网站首页>【锁】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"
边栏推荐
- ArrayList 扩容详解,扩容原理[通俗易懂]
- 定了!2022海南二级造价工程师考试时间确定!报名通道已开启!
- Is it reasonable and safe for securities companies to open accounts for 10000 free securities? How to say
- Buuctf reinforcement question ezsql
- 官宣:Apache Doris 顺利毕业,成为 ASF 顶级项目!
- The first word of JVM -- detailed introduction to JVM and analysis of runtime data area
- DirectX repair tool v4.1 public beta! [easy to understand]
- Error-tf.function-decorated function tried to create variables on non-first call
- Ubuntu 14.04下搭建MySQL主从服务器
- Some thoughts on software testing
猜你喜欢

Semiconductor foundation of binary realization principle
![[zero basic IOT pwn] reproduce Netgear wnap320 rce](/img/f7/d683df1d4b1b032164a529d3d94615.png)
[zero basic IOT pwn] reproduce Netgear wnap320 rce

互联网医院系统源码 医院小程序源码 智慧医院源码 在线问诊系统源码

What are the books that have greatly improved the thinking and ability of programming?

Today, with the popularity of micro services, how does service mesh exist?

Take you to API development by hand

Rearrangement of overloaded operators

C learning notes (5) class and inheritance

cmake 基本使用过程

【15. 区间合并】
随机推荐
网速、宽带、带宽、流量三者之间的关系是什么?
博文推荐 | 深入研究 Pulsar 中的消息分块
Solid smart contract development - easy to get started
cmake 基本使用过程
微服务开发步骤(nacos)
After twists and turns, I finally found the method of SRC vulnerability mining [recommended collection]
sqlilabs less10
写在Doris毕业后的第一天
Basic operations of SQL database
What is the relationship between network speed, broadband, bandwidth and traffic?
2022-2-15 learning the imitation Niuke project - post in Section 2
30 Devops interview questions and answers
深度分析数据在内存中的存储形式
643. Maximum average number of subarrays I
About the use of HTTP cache validation last modified and Etag
JVM second conversation -- JVM memory model and garbage collection
Music player development example (can be set up)
数字化转型:数据可视化赋能销售管理
数据产品经理需要掌握哪些数据能力?
idea中新建的XML文件变成普通文件的解决方法.