当前位置:网站首页>【锁】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"
边栏推荐
- Redis安装及Ubuntu 14.04下搭建ssdb主从环境
- 关于软件测试的一些思考
- tensorflow2-savedmodel convert to pb(frozen_graph)
- [zero basic IOT pwn] reproduce Netgear wnap320 rce
- The first technology podcast month will be broadcast soon
- 对于编程思想和能力有重大提升的书有哪些?
- 2022-2-15 learning xiangniuke project - Section 4 business management
- MongoDB第二话 -- MongoDB高可用集群实现
- 微服务开发步骤(nacos)
- 2022-2-15 learning xiangniuke project - Section 1 filtering sensitive words
猜你喜欢

cmake 基本使用过程

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

The first technology podcast month will be broadcast soon

How to view the state-owned enterprises have unloaded Microsoft office and switched to Kingsoft WPS?

Sqlachemy common operations
![[14. Interval sum (discretization)]](/img/e5/8b29aca7068a6385e8ce90c2742c37.png)
[14. Interval sum (discretization)]

2022-2-15 learning the imitation Niuke project - post in Section 2

Fundamentals of C language

C learning notes (5) class and inheritance

2022-2-15 learning xiangniuke project - Section 1 filtering sensitive words
随机推荐
首届技术播客月开播在即
Ensure production safety! Guangzhou requires hazardous chemical enterprises to "not produce in an unsafe way, and keep constant communication"
2022-2-15 learning the imitation Niuke project - Section 3 post details
Build your own website (14)
643. Maximum average number of subarrays I
Leetcode (69) -- square root of X
数据产品经理需要掌握哪些数据能力?
【14. 区间和(离散化)】
2022-2-15 learning xiangniuke project - Section 4 business management
Internet hospital system source code hospital applet source code smart hospital source code online consultation system source code
关于软件测试的一些思考
Apk signature principle
TypeScript:const
Pat 1065 a+b and C (64bit) (20 points) (16 points)
炎炎夏日,这份安全用气指南请街坊们收好!
Storage form of in-depth analysis data in memory
数字化转型:数据可视化赋能销售管理
The markdown editor uses basic syntax
What value can NPDP bring to product managers? Do you know everything?
Semiconductor foundation of binary realization principle