11package top .cadecode .uniboot .common .util ;
22
33import com .fasterxml .jackson .core .type .TypeReference ;
4- import lombok .RequiredArgsConstructor ;
54import org .springframework .beans .factory .InitializingBean ;
5+ import org .springframework .beans .factory .annotation .Autowired ;
66import org .springframework .data .redis .core .StringRedisTemplate ;
77import org .springframework .stereotype .Component ;
88
1515 * @author Cade Li
1616 * @date 2022/5/29
1717 */
18- @ RequiredArgsConstructor
1918@ Component
2019public class RedisUtil implements InitializingBean {
2120
21+ public static StringRedisTemplate TEMPLATE ;
22+
23+ private StringRedisTemplate stringRedisTemplate ;
24+
2225 /**
2326 * 自动注入 stringRedisTemplate
2427 */
25- private final StringRedisTemplate stringRedisTemplate ;
26-
27- public static StringRedisTemplate TEMPLATE ;
28+ @ Autowired (required = false )
29+ public void setStringRedisTemplate (StringRedisTemplate stringRedisTemplate ) {
30+ this .stringRedisTemplate = stringRedisTemplate ;
31+ }
2832
2933 /**
3034 * 获取 value
@@ -45,21 +49,45 @@ public static <T> T get(String key, TypeReference<T> typeReference) {
4549 /**
4650 * 添加 key
4751 */
52+ public static void set (String key , Object o ) {
53+ String json = JacksonUtil .toJson (o );
54+ TEMPLATE .opsForValue ().set (key , json );
55+ }
56+
57+ /**
58+ * 添加 key,如果不存在
59+ */
60+ public static Boolean setIfAbsent (String key , Object o ) {
61+ String json = JacksonUtil .toJson (o );
62+ return TEMPLATE .opsForValue ().setIfAbsent (key , json );
63+ }
64+
65+ /**
66+ * 添加 key,如果不存在
67+ */
68+ public static Boolean setIfPresent (String key , Object o ) {
69+ String json = JacksonUtil .toJson (o );
70+ return TEMPLATE .opsForValue ().setIfPresent (key , json );
71+ }
72+
73+ /**
74+ * 添加 key 并设置有效期
75+ */
4876 public static void set (String key , Object o , long timeout , TimeUnit timeUnit ) {
4977 String json = JacksonUtil .toJson (o );
5078 TEMPLATE .opsForValue ().set (key , json , timeout , timeUnit );
5179 }
5280
5381 /**
54- * 添加 key,如果不存在
82+ * 添加 key 并设置有效期 ,如果不存在
5583 */
5684 public static Boolean setIfAbsent (String key , Object o , long timeout , TimeUnit timeUnit ) {
5785 String json = JacksonUtil .toJson (o );
5886 return TEMPLATE .opsForValue ().setIfAbsent (key , json , timeout , timeUnit );
5987 }
6088
6189 /**
62- * 添加 key,如果不存在
90+ * 添加 key 并设置有效期 ,如果不存在
6391 */
6492 public static Boolean setIfPresent (String key , Object o , long timeout , TimeUnit timeUnit ) {
6593 String json = JacksonUtil .toJson (o );
@@ -91,7 +119,7 @@ public static Boolean expire(String key, long timeout, TimeUnit timeUnit) {
91119 public void afterPropertiesSet () {
92120 TEMPLATE = stringRedisTemplate ;
93121 if (Objects .isNull (TEMPLATE )) {
94- throw new IllegalArgumentException ("无法注入依赖: stringRedisTemplate" );
122+ throw new IllegalArgumentException ("Bean stringRedisTemplate not found " );
95123 }
96124 }
97125}
0 commit comments