Redis常用工具封装(RedisTemplate)

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description Redis工具类
 * @Author WangKun
 * @Date 2023/2/24 15:43
 * @Version
 */
@Component
public class RedisTemplateUtil {

//    @Autowired
    private static RedisTemplate<String, Object> redisTemplate;

    // 采用set方法注入
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate){
        RedisTemplateUtil.redisTemplate = redisTemplate;
    }

    /**
     * @param key
     * @param time 时间(秒)
     * @Description key指定失效时间
     * @Throws
     * @Return boolean
     * @Date 2023-02-24 15:46:15
     * @Author WangKun
     */
    public static boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key
     * @Description 根据key 获取过期时间
     * @Throws
     * @Return long 时间(秒) 返回0代表为永久有效
     * @Date 2023-02-24 15:47:54
     * @Author WangKun
     */
    public static long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * @param key
     * @Description 判断key是否存在
     * @Throws
     * @Return boolean true:存在,false:不存在
     * @Date 2023-02-24 15:48:43
     * @Author WangKun
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key 多个使用逗号隔开
     * @Description 删除缓存
     * @Throws
     * @Return void
     * @Date 2023-02-24 15:50:24
     * @Author WangKun
     */
    @SuppressWarnings("unchecked")
    public static void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * @param key
     * @Description 获取缓存值
     * @Throws
     * @Return java.lang.Object
     * @Date 2023-02-24 15:51:21
     * @Author WangKun
     */
    public static Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * @param key
     * @param clazz
     * @Description 获取缓存值, 指定类型
     * @Throws
     * @Return T
     * @Date 2023-02-24 15:53:45
     * @Author WangKun
     */
    public static <T> T get(String key, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        Object v = get(key);
        if (v == null) return null;
        return mapper.convertValue(v, clazz);
    }

    /**
     * @param key
     * @param clazz 实体类型
     * @Description 获取缓存值, 指定类型
     * @Throws
     * @Return java.util.List<T>
     * @Date 2023-02-27 17:57:13
     * @Author WangKun
     */
    public static <T> List<T> get2(String key, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        ObjectMapper objectMapper = new ObjectMapper();
        Object obj = get(key);
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                result.add(objectMapper.convertValue(o, clazz));
            }
        }
        return result;
    }

    /**
     * @param key 键 value 值
     * @Description 缓存放入
     * @Throws
     * @Return true成功 false失败
     * @Date 2023-02-24 15:52:11
     * @Author WangKun
     */
    public static boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key 键 value 值 time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @Description 缓存放入并设置时间
     * @Throws
     * @Return
     * @Date 2023-02-24 15:54:58
     * @Author WangKun
     */
    public static boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 定义一个 RedisUtil 工具类,该类中包含 RedisTemplate 的实例化和常用操作方法。 ``` @Component public class RedisUtil { @Autowired private RedisTemplate redisTemplate; /** * 设置过期时间 * * @param key 键 * @param expire 过期时间(秒) * @return boolean */ public boolean expire(String key, long expire) { try { if (expire > 0) { redisTemplate.expire(key, expire, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 获取过期时间 * * @param key 键 * @return long */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断 key 是否存在 * * @param key 键 * @return boolean */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除 key * * @param key 键 */ @SuppressWarnings("unchecked") public void delete(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } /** * 获取 value * * @param key 键 * @return Object */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 设置 value * * @param key 键 * @param value 值 * @return boolean */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 设置 value 并设置过期时间 * * @param key 键 * @param value 值 * @param expire 过期时间(秒) * @return boolean */ public boolean set(String key, Object value, long expire) { try { if (expire > 0) { redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 获取 list 中所有元素 * * @param key 键 * @return List<Object> */ public List<Object> lGet(String key) { try { return redisTemplate.opsForList().range(key, 0, -1); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取 list 中指定范围的元素 * * @param key 键 * @param start 起始索引 * @param end 结束索引 * @return List<Object> */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取 list 的长度 * * @param key 键 * @return long */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引获取 list 中的值 * * @param key 键 * @param index 索引 * @return Object */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将一个或多个值插入到 list 头部 * * @param key 键 * @param value 值 * @return long */ public long lLeftPush(String key, Object... value) { try { return redisTemplate.opsForList().leftPushAll(key, value); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将一个或多个值插入到 list 尾部 * * @param key 键 * @param value 值 * @return long */ public long lRightPush(String key, Object... value) { try { return redisTemplate.opsForList().rightPushAll(key, value); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引设置 list 中的值 * * @param key 键 * @param index 索引 * @param value 值 * @return boolean */ public boolean lSetIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除 list 中的值 * * @param key 键 * @param count 移除数量(0:删除所有值;大于 0:从头部开始删除指定数量的值;小于 0:从尾部开始删除指定数量的值) * @param value 值 * @return long */ public long lRemove(String key, long count, Object value) { try { return redisTemplate.opsForList().remove(key, count, value); } catch (Exception e) { e.printStackTrace(); return 0; } } } ``` 2. 在需要使用 Redis 操作的类中注入 RedisUtil 类,即可使用 RedisUtil 中的方法操作 Redis。 ``` @Service public class DemoService { @Autowired private RedisUtil redisUtil; public void demo() { // 判断 key 是否存在 boolean hasKey = redisUtil.hasKey("test_key"); System.out.println(hasKey); // 设置 value redisUtil.set("test_key", "test_value"); // 获取 value Object value = redisUtil.get("test_key"); System.out.println(value); // 设置 list redisUtil.lRightPush("test_list", "1", "2", "3", "4", "5"); // 获取 list 中所有元素 List<Object> list1 = redisUtil.lGet("test_list"); System.out.println(list1); // 获取 list 中指定范围的元素 List<Object> list2 = redisUtil.lGet("test_list", 0, 2); System.out.println(list2); // 获取 list 的长度 long size = redisUtil.lGetListSize("test_list"); System.out.println(size); // 通过索引获取 list 中的值 Object indexValue = redisUtil.lGetIndex("test_list", 2); System.out.println(indexValue); // 通过索引设置 list 中的值 redisUtil.lSetIndex("test_list", 2, "new_value"); // 移除 list 中的值 long count = redisUtil.lRemove("test_list", 0, "new_value"); System.out.println(count); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值