66import org .springframework .data .redis .core .StringRedisTemplate ;
77import org .springframework .stereotype .Component ;
88
9+ import java .util .Objects ;
910import 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
1819public 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