Skip to content

Commit 0eb546f

Browse files
committed
feat: 优化 Redis 工具类,添加 setnx 相关方法
1 parent 28f2bb2 commit 0eb546f

1 file changed

Lines changed: 29 additions & 2 deletions

File tree

  • simple-common/src/main/java/top/cadecode/sra/common/util

simple-common/src/main/java/top/cadecode/sra/common/util/RedisUtil.java

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,16 @@
66
import org.springframework.data.redis.core.StringRedisTemplate;
77
import org.springframework.stereotype.Component;
88

9+
import java.util.Objects;
910
import java.util.concurrent.TimeUnit;
1011

1112
/**
1213
* @author Cade Li
1314
* @date 2022/5/29
1415
* @description Redis 工具类
1516
*/
16-
@Component
1717
@RequiredArgsConstructor
18+
@Component
1819
public class RedisUtil implements InitializingBean {
1920

2021
/**
@@ -48,6 +49,22 @@ public static void set(String key, Object o, long timeout, TimeUnit timeUnit) {
4849
TEMPLATE.opsForValue().set(key, json, timeout, timeUnit);
4950
}
5051

52+
/**
53+
* 添加 key,如果不存在
54+
*/
55+
public static Boolean setIfAbsent(String key, Object o, long timeout, TimeUnit timeUnit) {
56+
String json = JacksonUtil.toJson(o);
57+
return TEMPLATE.opsForValue().setIfAbsent(key, json, timeout, timeUnit);
58+
}
59+
60+
/**
61+
* 添加 key,如果不存在
62+
*/
63+
public static Boolean setIfPresent(String key, Object o, long timeout, TimeUnit timeUnit) {
64+
String json = JacksonUtil.toJson(o);
65+
return TEMPLATE.opsForValue().setIfPresent(key, json, timeout, timeUnit);
66+
}
67+
5168
/**
5269
* 删除 key
5370
*/
@@ -56,7 +73,14 @@ public static Boolean del(String key) {
5673
}
5774

5875
/**
59-
* 删除 key
76+
* 是否存在 key
77+
*/
78+
public static Boolean has(String key) {
79+
return TEMPLATE.hasKey(key);
80+
}
81+
82+
/**
83+
* 设置 key 过期时间
6084
*/
6185
public static Boolean expire(String key, long timeout, TimeUnit timeUnit) {
6286
return TEMPLATE.expire(key, timeout, timeUnit);
@@ -65,5 +89,8 @@ public static Boolean expire(String key, long timeout, TimeUnit timeUnit) {
6589
@Override
6690
public void afterPropertiesSet() {
6791
TEMPLATE = stringRedisTemplate;
92+
if (Objects.isNull(TEMPLATE)) {
93+
throw new IllegalArgumentException("无法注入依赖:stringRedisTemplate");
94+
}
6895
}
6996
}

0 commit comments

Comments
 (0)