|
| 1 | +package top.cadecode.sra.framework.util; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import org.springframework.beans.factory.InitializingBean; |
| 6 | +import org.springframework.data.redis.core.RedisTemplate; |
| 7 | +import org.springframework.stereotype.Component; |
| 8 | + |
| 9 | +import java.util.concurrent.TimeUnit; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author Cade Li |
| 13 | + * @date 2022/5/29 |
| 14 | + * @description Redis 工具类 |
| 15 | + */ |
| 16 | +@Component |
| 17 | +@RequiredArgsConstructor |
| 18 | +public class RedisUtil implements InitializingBean { |
| 19 | + |
| 20 | + /** |
| 21 | + * 自动注入 redisTemplate |
| 22 | + */ |
| 23 | + private final RedisTemplate<String, Object> redisTemplate; |
| 24 | + |
| 25 | + private static RedisTemplate<String, Object> TEMPLATE; |
| 26 | + |
| 27 | + /** |
| 28 | + * 获取 value 并强转 |
| 29 | + */ |
| 30 | + @SuppressWarnings("unchecked") |
| 31 | + public static <T> T get(String key, Class<T> clazz) { |
| 32 | + return (T) TEMPLATE.opsForValue().get(key); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * 获取 value 并强转,带泛型 |
| 37 | + */ |
| 38 | + @SuppressWarnings("unchecked") |
| 39 | + public static <T> T get(String key, TypeReference<T> typeReference) { |
| 40 | + return (T) TEMPLATE.opsForValue().get(key); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * 添加 key |
| 45 | + */ |
| 46 | + public static void set(String key, Object o, long timeout, TimeUnit timeUnit) { |
| 47 | + TEMPLATE.opsForValue().set(key, o, timeout, timeUnit); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * 删除 key |
| 52 | + */ |
| 53 | + public static Boolean del(String key) { |
| 54 | + return TEMPLATE.delete(key); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * 删除 key |
| 59 | + */ |
| 60 | + public static Boolean del(String key, long timeout, TimeUnit timeUnit) { |
| 61 | + return TEMPLATE.expire(key, timeout, timeUnit); |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public void afterPropertiesSet() { |
| 66 | + TEMPLATE = redisTemplate; |
| 67 | + } |
| 68 | +} |
0 commit comments