当前位置:网站首页>【锁】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"
边栏推荐
- Research Report on the development trend and competitive strategy of the global camera filter bracket industry
- [zero basic IOT pwn] reproduce Netgear wnap320 rce
- Develop small programs and official account from zero [phase III]
- Research Report on the development trend and competitive strategy of the global diamond suspension industry
- 数字化转型:数据可视化赋能销售管理
- 【牛客网刷题系列 之 Verilog快速入门】~ 使用函数实现数据大小端转换
- 定了!2022海南二级造价工程师考试时间确定!报名通道已开启!
- C learning notes (5) class and inheritance
- Mongodb second call -- implementation of mongodb high availability cluster
- 手把手带你入门 API 开发
猜你喜欢

竣达技术丨室内空气环境监测终端 pm2.5、温湿度TVOC等多参数监测

建立自己的网站(14)

241. 为运算表达式设计优先级

炎炎夏日,这份安全用气指南请街坊们收好!

Leetcode (69) -- square root of X

JVM performance tuning and practical basic theory part II

首届技术播客月开播在即

Opencv interpolation mode

The State Administration of Chia Tai market supervision, the national development and Reform Commission and the China Securities Regulatory Commission jointly reminded and warned some iron ores

Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models
随机推荐
官宣:Apache Doris 顺利毕业,成为 ASF 顶级项目!
[zero basic IOT pwn] reproduce Netgear wnap320 rce
数据产品经理需要掌握哪些数据能力?
生成随机数(4位、6位)
Tensorflow 2. X realizes iris classification
C 语言基础
Word2vec yyds dry goods inventory
Vnctf2022 open web gocalc0
Written on the first day after Doris graduated
Don't want to knock the code? Here comes the chance
Internet hospital system source code hospital applet source code smart hospital source code online consultation system source code
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
What is the relationship between network speed, broadband, bandwidth and traffic?
TypeScript: let
职场太老实,总被欺负怎么办?
Filter &(登录拦截)
Zabbix API与PHP的配置
cmake 基本使用过程
[dynamic programming] interval dp:p1005 matrix retrieval
Markdown编辑器使用基本语法