RedisCache redis工具类

public class RedisCache {

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存的基本对象。Integer String 实体类
     *
     * @param key  缓存的键值
     * @param value 缓存的值
     * @param <T>
     * @return    缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value){
        ValueOperations<String, T> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        return operations;
    }

    /**
     *
     * @param key  缓存的键值
     * @param value  缓存的值
     * @param timeout  时间
     * @param timeUnit  时间颗粒度
     * @param <T>
     * @return   缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit){
        ValueOperations<String, T> operations = redisTemplate.opsForValue();
        operations.set(key, value, timeout, timeUnit);
        return operations;
    }

    /**
     * 获得缓存的基本对象
     *
     * @param key   缓存键值
     * @param <T>
     * @return   缓存键值对应的数据
     */
    public <T> T getCacheObject(String key){
        ValueOperations<String, T> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public void deleteObject(String  key){
        redisTemplate.delete(key);
    }


    /**
     * 删除集合对象
     *
     * @param collection
     */
    public void deleteObject(Collection collection){
        redisTemplate.delete(collection);
    }


    /**
     * 缓存list数据
     *
     * @param key    缓存的键值
     * @param dataList    带缓存的list数据
     * @param <T>
     * @return    缓存的对象
     */
    public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList){
        ListOperations<String, T> listOperations = redisTemplate.opsForList();
        if (dataList != null) {
            int size = dataList.size();
            for (int i = 0; i < size; i++) {
                listOperations.leftPush(key, dataList.get(i));
            }
        }
        return listOperations;
    }


    /**
     *  获得缓存的list对象
     *
     * @param key  缓存的键值
     * @param <T>
     * @return   缓存键值对应的集合数据
     */
    public  <T> List<T> getCacheList(String key){
        List<T> list = new ArrayList<>();
        ListOperations<String, T> listOperations = redisTemplate.opsForList();
        Long size = listOperations.size(key);

        for (int i = 0; i < size; i++) {
            list.add(listOperations.index(key, i));
        }
        return list;
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(String key) {
        Set<T> dataSet = new HashSet<T>();
        BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
        dataSet = operation.members();
        return dataSet;
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap)
        {
            for (Map.Entry<String, T> entry : dataMap.entrySet())
            {
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }
        }
        return hashOperations;
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(String key) {
        Map<String, T> map = redisTemplate.opsForHash().entries(key);
        return map;
    }

    /**
     *获得缓存的基本对象列表
     * @param pattern  字符串前缀
     * @return
     */
    public Collection<String> keys(String pattern){
        return redisTemplate.keys(pattern);
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以为你提供一个Redis缓存工具类的示例: import redis class RedisCache: def __init__(self, host, port, db): self.redis = redis.StrictRedis(host=host, port=port, db=db) def get(self, key): return self.redis.get(key) def set(self, key, value): self.redis.set(key, value) def delete(self, key): self.redis.delete(key) def flushall(self): self.redis.flushall() ### 回答2: Redis缓存工具类是一个用于简化和优化Redis缓存操作的工具类。下面是一个简单的示例: ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisCacheUtil { private static JedisPool jedisPool; /** * 初始化Jedis连接池 */ static { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(100); // 最大连接数 config.setMaxIdle(20); // 最大空闲连接数 config.setTestOnBorrow(true); // 尝试借用一个连接时,是否进行有效性检测 jedisPool = new JedisPool(config, "localhost", 6379); // Redis连接信息 } /** * 从连接池获取Jedis实例 */ public static Jedis getJedis() { return jedisPool.getResource(); } /** * 将Jedis实例返回到连接池 */ public static void closeJedis(Jedis jedis) { if (jedis != null) { jedis.close(); } } /** * 设置缓存 */ public static void set(String key, String value) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.set(key, value); } finally { closeJedis(jedis); } } /** * 根据key获取缓存值 */ public static String get(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.get(key); } finally { closeJedis(jedis); } } /** * 删除缓存 */ public static void delete(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.del(key); } finally { closeJedis(jedis); } } } ``` 使用该工具类,可以通过简单的方法调用来实现Redis缓存的各种操作。示例如下: ```java public class RedisDemo { public static void main(String[] args) { RedisCacheUtil.set("key1", "value"); // 设置缓存 String value = RedisCacheUtil.get("key1"); // 获取缓存 System.out.println(value); RedisCacheUtil.delete("key1"); // 删除缓存 value = RedisCacheUtil.get("key1"); // 获取缓存 System.out.println(value); // 输出null } } ``` 通过使用这个简单的Redis缓存工具类,可以方便地进行Redis缓存的操作,提高缓存的效率和可维护性。当然,实际的缓存操作可以根据具体需求进行扩展和优化。 ### 回答3: Redis缓存工具类是用于简化与Redis数据库交互的工具。下面是一个示例实现: ``` import redis import pickle class RedisCache: def __init__(self, host, port, db): self.redis = redis.Redis(host=host, port=port, db=db) def set(self, key, value, expire=None): pickled_value = pickle.dumps(value) self.redis.set(key, pickled_value) if expire: self.redis.expire(key, expire) def get(self, key): pickled_value = self.redis.get(key) if pickled_value is not None: value = pickle.loads(pickled_value) return value return None def delete(self, key): self.redis.delete(key) def exists(self, key): return self.redis.exists(key) ``` 使用示例: ``` cache = RedisCache(host='localhost', port=6379, db=0) # 设置缓存 cache.set('user:1', {'name': 'Alice', 'age': 25}, expire=3600) # 获取缓存 user = cache.get('user:1') print(user) # 输出: {'name': 'Alice', 'age': 25} # 删除缓存 cache.delete('user:1') # 检查缓存是否存在 if cache.exists('user:1'): print('缓存存在') else: print('缓存不存在') ``` 这个简单的Redis缓存工具类封装了常用的操作方法,如set、get、delete和exists,并使用pickle模块将Python对象序列化成字符串再存储到Redis数据库中,以实现缓存数据的存储和获取。还可以通过设置过期时间来控制缓存的有效期。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值