zoukankan      html  css  js  c++  java
  • SpringBoot 使用RedisTemplate操作Redis

    Redis工具类(旧版本)

    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    
    /**
     * Created by qhong on 2018/6/5 17:08
     **/
    @Component
    public class RedisUtil {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        //=============================common============================
        /**
         * 指定缓存失效时间
         * @param key 键
         * @param time 时间(秒)
         * @return
         */
        public 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;
            }
        }
    
        /**
         * 根据key 获取过期时间
         * @param key 键 不能为null
         * @return 时间(秒) 返回0代表为永久有效
         */
        public long getExpire(String key){
            return redisTemplate.getExpire(key,TimeUnit.SECONDS);
        }
    
        /**
         * 判断key是否存在
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key){
            try {
                return redisTemplate.hasKey(key);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 删除缓存
         * @param key 可以传一个值 或多个
         */
        @SuppressWarnings("unchecked")
        public void del(String ... key){
            if(key!=null&&key.length>0){
                if(key.length==1){
                    redisTemplate.delete(key[0]);
                }else{
                    redisTemplate.delete(CollectionUtils.arrayToList(key));
                }
            }
        }
    
        //============================String=============================
        /**
         * 普通缓存获取
         * @param key 键
         * @return 值
         */
        public Object get(String key){
            return key==null?null:redisTemplate.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         * @param key 键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key,Object value) {
            try {
                redisTemplate.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
        }
    
        /**
         * 普通缓存放入并设置时间
         * @param key 键
         * @param value 值
         * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
         * @return true成功 false 失败
         */
        public 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;
            }
        }
    
        /**
         * 递增
         * @param key 键
         * @param by 要增加几(大于0)
         * @return
         */
        public long incr(String key, long delta){
            if(delta<0){
                throw new RuntimeException("递增因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, delta);
        }
    
        /**
         * 递减
         * @param key 键
         * @param by 要减少几(小于0)
         * @return
         */
        public long decr(String key, long delta){
            if(delta<0){
                throw new RuntimeException("递减因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, -delta);
        }
    
        //================================Map=================================
        /**
         * HashGet
         * @param key 键 不能为null
         * @param item 项 不能为null
         * @return 值
         */
        public Object hget(String key,String item){
            return redisTemplate.opsForHash().get(key, item);
        }
    
        /**
         * 获取hashKey对应的所有键值
         * @param key 键
         * @return 对应的多个键值
         */
        public Map<Object,Object> hmget(String key){
            return redisTemplate.opsForHash().entries(key);
        }
    
        /**
         * HashSet
         * @param key 键
         * @param map 对应多个键值
         * @return true 成功 false 失败
         */
        public boolean hmset(String key, Map<String,Object> map){
            try {
                redisTemplate.opsForHash().putAll(key, map);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * HashSet 并设置时间
         * @param key 键
         * @param map 对应多个键值
         * @param time 时间(秒)
         * @return true成功 false失败
         */
        public boolean hmset(String key, Map<String,Object> map, long time){
            try {
                redisTemplate.opsForHash().putAll(key, map);
                if(time>0){
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         * @param key 键
         * @param item 项
         * @param value 值
         * @return true 成功 false失败
         */
        public boolean hset(String key,String item,Object value) {
            try {
                redisTemplate.opsForHash().put(key, item, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         * @param key 键
         * @param item 项
         * @param value 值
         * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
         * @return true 成功 false失败
         */
        public boolean hset(String key,String item,Object value,long time) {
            try {
                redisTemplate.opsForHash().put(key, item, value);
                if(time>0){
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 删除hash表中的值
         * @param key 键 不能为null
         * @param item 项 可以使多个 不能为null
         */
        public void hdel(String key, Object... item){
            redisTemplate.opsForHash().delete(key,item);
        }
    
        /**
         * 判断hash表中是否有该项的值
         * @param key 键 不能为null
         * @param item 项 不能为null
         * @return true 存在 false不存在
         */
        public boolean hHasKey(String key, String item){
            return redisTemplate.opsForHash().hasKey(key, item);
        }
    
        /**
         * hash递增 如果不存在,就会创建一个 并把新增后的值返回
         * @param key 键
         * @param item 项
         * @param by 要增加几(大于0)
         * @return
         */
        public double hincr(String key, String item,double by){
            return redisTemplate.opsForHash().increment(key, item, by);
        }
    
        /**
         * hash递减
         * @param key 键
         * @param item 项
         * @param by 要减少记(小于0)
         * @return
         */
        public double hdecr(String key, String item,double by){
            return redisTemplate.opsForHash().increment(key, item,-by);
        }
    
        //============================set=============================
        /**
         * 根据key获取Set中的所有值
         * @param key 键
         * @return
         */
        public Set<Object> sGet(String key){
            try {
                return redisTemplate.opsForSet().members(key);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 根据value从一个set中查询,是否存在
         * @param key 键
         * @param value 值
         * @return true 存在 false不存在
         */
        public boolean sHasKey(String key,Object value){
            try {
                return redisTemplate.opsForSet().isMember(key, value);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将数据放入set缓存
         * @param key 键
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSet(String key, Object...values) {
            try {
                return redisTemplate.opsForSet().add(key, values);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 将set数据放入缓存
         * @param key 键
         * @param time 时间(秒)
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSetAndTime(String key,long time,Object...values) {
            try {
                Long count = redisTemplate.opsForSet().add(key, values);
                if(time>0) expire(key, time);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 获取set缓存的长度
         * @param key 键
         * @return
         */
        public long sGetSetSize(String key){
            try {
                return redisTemplate.opsForSet().size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 移除值为value的
         * @param key 键
         * @param values 值 可以是多个
         * @return 移除的个数
         */
        public long setRemove(String key, Object ...values) {
            try {
                Long count = redisTemplate.opsForSet().remove(key, values);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
        //===============================list=================================
    
        /**
         * 获取list缓存的内容
         * @param key 键
         * @param start 开始
         * @param end 结束  0 到 -1代表所有值
         * @return
         */
        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
         */
        public List<Object> lGetAll(String key){
            return lGet(key,0,-1);
        }
    
        /**
         * 获取list缓存的长度
         * @param key 键
         * @return
         */
        public long lGetListSize(String key){
            try {
                return redisTemplate.opsForList().size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 通过索引 获取list中的值
         * @param key 键
         * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
         * @return
         */
        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 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, Object value) {
            try {
                redisTemplate.opsForList().rightPush(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, Object value, long time) {
            try {
                redisTemplate.opsForList().rightPush(key, value);
                if (time > 0) expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, List<Object> value) {
            try {
                redisTemplate.opsForList().rightPushAll(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, List<Object> value, long time) {
            try {
                redisTemplate.opsForList().rightPushAll(key, value);
                if (time > 0) expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 根据索引修改list中的某条数据
         * @param key 键
         * @param index 索引
         * @param value 值
         * @return
         */
        public boolean lUpdateIndex(String key, long index,Object value) {
            try {
                redisTemplate.opsForList().set(key, index, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 移除N个值为value
         * @param key 键
         * @param count 移除多少个
         * @param value 值
         * @return 移除的个数
         */
        public long lRemove(String key,long count,Object value) {
            try {
                Long remove = redisTemplate.opsForList().remove(key, count, value);
                return remove;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    }
    View Code

    新版:

    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.HashOperations;
    import org.springframework.data.redis.core.ListOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.SetOperations;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.data.redis.core.ZSetOperations;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    
    /**
     * Created by qhong on 2018/6/5 17:08
     **/
    @Component
    public class RedisUtil {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ValueOperations<String, String> valueOperations;
        @Autowired
        private HashOperations<String, String, Object> hashOperations;
        @Autowired
        private ListOperations<String, Object> listOperations;
        @Autowired
        private SetOperations<String, Object> setOperations;
        @Autowired
        private ZSetOperations<String, Object> zSetOperations;
    
        //=============================common============================
        /**
         * 指定缓存失效时间
         * @param key 键
         * @param time 时间(秒)
         * @return
         */
        public 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;
            }
        }
    
        /**
         * 根据key 获取过期时间
         * @param key 键 不能为null
         * @return 时间(秒) 返回0代表为永久有效
         */
        public long getExpire(String key){
            return redisTemplate.getExpire(key,TimeUnit.SECONDS);
        }
    
        /**
         * 判断key是否存在
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key){
            try {
                return redisTemplate.hasKey(key);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 删除缓存
         * @param key 可以传一个值 或多个
         */
        @SuppressWarnings("unchecked")
        public void del(String ... key){
            if(key!=null&&key.length>0){
                if(key.length==1){
                    redisTemplate.delete(key[0]);
                }else{
                    redisTemplate.delete(CollectionUtils.arrayToList(key));
                }
            }
        }
    
        //============================String=============================
        /**
         * 普通缓存获取
         * @param key 键
         * @return 值
         */
        public Object get(String key){
            return key==null?null:valueOperations.get(key);
        }
    
        /**
         * 普通缓存放入
         * @param key 键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key,Object value) {
            try {
                valueOperations.set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
        }
    
        /**
         * 普通缓存放入并设置时间
         * @param key 键
         * @param value 值
         * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
         * @return true成功 false 失败
         */
        public boolean set(String key,Object value,long time){
            try {
                if(time>0){
                    valueOperations.set(key, value, time, TimeUnit.SECONDS);
                }else{
                    set(key, value);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 递增
         * @param key 键
         * @param by 要增加几(大于0)
         * @return
         */
        public long incr(String key, long delta){
            if(delta<0){
                throw new RuntimeException("递增因子必须大于0");
            }
            return valueOperations.increment(key, delta);
        }
    
        /**
         * 递减
         * @param key 键
         * @param by 要减少几(小于0)
         * @return
         */
        public long decr(String key, long delta){
            if(delta<0){
                throw new RuntimeException("递减因子必须大于0");
            }
            return valueOperations.increment(key, -delta);
        }
    
        //================================Map=================================
        /**
         * HashGet
         * @param key 键 不能为null
         * @param item 项 不能为null
         * @return 值
         */
        public Object hget(String key,String item){
            return hashOperations.get(key, item);
        }
    
        /**
         * 获取hashKey对应的所有键值
         * @param key 键
         * @return 对应的多个键值
         */
        public Map<Object,Object> hmget(String key){
            return hashOperations.entries(key);
        }
    
        /**
         * HashSet
         * @param key 键
         * @param map 对应多个键值
         * @return true 成功 false 失败
         */
        public boolean hmset(String key, Map<String,Object> map){
            try {
                hashOperations.putAll(key, map);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * HashSet 并设置时间
         * @param key 键
         * @param map 对应多个键值
         * @param time 时间(秒)
         * @return true成功 false失败
         */
        public boolean hmset(String key, Map<String,Object> map, long time){
            try {
                hashOperations.putAll(key, map);
                if(time>0){
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         * @param key 键
         * @param item 项
         * @param value 值
         * @return true 成功 false失败
         */
        public boolean hset(String key,String item,Object value) {
            try {
                hashOperations.put(key, item, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         * @param key 键
         * @param item 项
         * @param value 值
         * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
         * @return true 成功 false失败
         */
        public boolean hset(String key,String item,Object value,long time) {
            try {
                hashOperations.put(key, item, value);
                if(time>0){
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 删除hash表中的值
         * @param key 键 不能为null
         * @param item 项 可以使多个 不能为null
         */
        public void hdel(String key, Object... item){
            hashOperations.delete(key,item);
        }
    
        /**
         * 判断hash表中是否有该项的值
         * @param key 键 不能为null
         * @param item 项 不能为null
         * @return true 存在 false不存在
         */
        public boolean hHasKey(String key, String item){
            return hashOperations.hasKey(key, item);
        }
    
        /**
         * hash递增 如果不存在,就会创建一个 并把新增后的值返回
         * @param key 键
         * @param item 项
         * @param by 要增加几(大于0)
         * @return
         */
        public double hincr(String key, String item,double by){
            return hashOperations.increment(key, item, by);
        }
    
        /**
         * hash递减
         * @param key 键
         * @param item 项
         * @param by 要减少记(小于0)
         * @return
         */
        public double hdecr(String key, String item,double by){
            return hashOperations.increment(key, item,-by);
        }
    
        //============================set=============================
        /**
         * 根据key获取Set中的所有值
         * @param key 键
         * @return
         */
        public Set<Object> sGet(String key){
            try {
                return setOperations.members(key);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 根据value从一个set中查询,是否存在
         * @param key 键
         * @param value 值
         * @return true 存在 false不存在
         */
        public boolean sHasKey(String key,Object value){
            try {
                return setOperations.isMember(key, value);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将数据放入set缓存
         * @param key 键
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSet(String key, Object...values) {
            try {
                return setOperations.add(key, values);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 将set数据放入缓存
         * @param key 键
         * @param time 时间(秒)
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSetAndTime(String key,long time,Object...values) {
            try {
                Long count = setOperations.add(key, values);
                if(time>0) expire(key, time);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 获取set缓存的长度
         * @param key 键
         * @return
         */
        public long sGetSetSize(String key){
            try {
                return setOperations.size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 移除值为value的
         * @param key 键
         * @param values 值 可以是多个
         * @return 移除的个数
         */
        public long setRemove(String key, Object ...values) {
            try {
                Long count = setOperations.remove(key, values);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
        //===============================list=================================
    
        /**
         * 获取list缓存的内容
         * @param key 键
         * @param start 开始
         * @param end 结束  0 到 -1代表所有值
         * @return
         */
        public List<Object> lGet(String key, long start, long end){
            try {
                return listOperations.range(key, start, end);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 获取list缓存的所有内容
         * @param key
         * @return
         */
        public List<Object> lGetAll(String key){
            return lGet(key,0,-1);
        }
    
        /**
         * 获取list缓存的长度
         * @param key 键
         * @return
         */
        public long lGetListSize(String key){
            try {
                return listOperations.size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        /**
         * 通过索引 获取list中的值
         * @param key 键
         * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
         * @return
         */
        public Object lGetIndex(String key,long index){
            try {
                return listOperations.index(key, index);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, Object value) {
            try {
                listOperations.rightPush(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, Object value, long time) {
            try {
                listOperations.rightPush(key, value);
                if (time > 0) expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, List<Object> value) {
            try {
                listOperations.rightPushAll(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将list放入缓存
         * @param key 键
         * @param value 值
         * @param time 时间(秒)
         * @return
         */
        public boolean lSet(String key, List<Object> value, long time) {
            try {
                listOperations.rightPushAll(key, value);
                if (time > 0) expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 根据索引修改list中的某条数据
         * @param key 键
         * @param index 索引
         * @param value 值
         * @return
         */
        public boolean lUpdateIndex(String key, long index,Object value) {
            try {
                listOperations.set(key, index, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 移除N个值为value
         * @param key 键
         * @param count 移除多少个
         * @param value 值
         * @return 移除的个数
         */
        public long lRemove(String key,long count,Object value) {
            try {
                Long remove = listOperations.remove(key, count, value);
                return remove;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    }

    RedisConfig:

    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.HashOperations;
    import org.springframework.data.redis.core.ListOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.SetOperations;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.data.redis.core.ZSetOperations;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
     * Created by qhong on 2018/6/5 17:31
     **/
    @Configuration
    public class RedisConfig {
        @Autowired
        private RedisConnectionFactory factory;
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(factory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.setHashKeySerializer(jackson2JsonRedisSerializer);
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.setDefaultSerializer(new StringRedisSerializer());
            template.afterPropertiesSet();
            return template;
        }
    
        @Bean
        public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
            return redisTemplate.opsForHash();
        }
    
        @Bean
        public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
            return redisTemplate.opsForValue();
        }
    
        @Bean
        public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
            return redisTemplate.opsForList();
        }
    
        @Bean
        public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
            return redisTemplate.opsForSet();
        }
    
        @Bean
        public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
            return redisTemplate.opsForZSet();
        }
    }

    application.properties:

    # REDIS (RedisProperties)
    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=127.0.0.1
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=0

     上面的例子还是有问题的

    主要是RedisTemplate序列化问题

    特别是在使用数组操作的时候

    仅供参考学习

    当然也可以使用其他方式解决这些序列化问题 ,就是转换成字符串,但是不喜欢

    /**
     * Created by qhong on 2018/6/7 10:25
     **/
    public class RedisCacheUtil {
    
        private static RedisTemplate<String, String> redisTemplate;
    
        public void setRedisTemplate(RedisTemplate<String, String> redisTemp) {
            redisTemplate = redisTemp;
        }
    
        /* ----------- common --------- */
        public static Collection<String> keys(String pattern) {
            return redisTemplate.keys(pattern);
        }
    
        public static void delete(String key) {
            redisTemplate.delete(key);
        }
    
        public static void delete(Collection<String> key) {
            redisTemplate.delete(key);
        }
    
        /* ----------- string --------- */
        public static <T> T get(String key, Class<T> clazz) {
            String value = redisTemplate.opsForValue().get(key);
            return parseJson(value, clazz);
        }
    
        public static <T> List<T> mget(Collection<String> keys, Class<T> clazz) {
            List<String> values = redisTemplate.opsForValue().multiGet(keys);
            return parseJsonList(values, clazz);
        }
    
        public static <T> void set(String key, T obj, Long timeout, TimeUnit unit) {
            if (obj == null) {
                return;
            }
    
            String value = toJson(obj);
            if (timeout != null) {
                redisTemplate.opsForValue().set(key, value, timeout, unit);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
        }
    
        public static <T> T getAndSet(String key, T obj, Class<T> clazz) {
            if (obj == null) {
                return get(key, clazz);
            }
    
            String value = redisTemplate.opsForValue().getAndSet(key, toJson(obj));
            return parseJson(value, clazz);
        }
    
        public static int decrement(String key, int delta) {
            Long value = redisTemplate.opsForValue().increment(key, -delta);
            return value.intValue();
        }
    
        public static int increment(String key, int delta) {
            Long value = redisTemplate.opsForValue().increment(key, delta);
            return value.intValue();
        }
    
        /* ----------- list --------- */
        public static int size(String key) {
            return redisTemplate.opsForList().size(key).intValue();
        }
    
        public static <T> List<T> range(String key, long start, long end, Class<T> clazz) {
            List<String> list = redisTemplate.opsForList().range(key, start, end);
            return parseJsonList(list, clazz);
        }
    
        public static void rightPushAll(String key, Collection<?> values, Long timeout,
                                        TimeUnit unit) {
            if (values == null || values.isEmpty()) {
                return;
            }
    
            redisTemplate.opsForList().rightPushAll(key, toJsonList(values));
            if (timeout != null) {
                redisTemplate.expire(key, timeout, unit);
            }
        }
    
        public static <T> void leftPush(String key, T obj) {
            if (obj == null) {
                return;
            }
    
            redisTemplate.opsForList().leftPush(key, toJson(obj));
        }
    
        public static <T> T leftPop(String key, Class<T> clazz) {
            String value = redisTemplate.opsForList().leftPop(key);
            return parseJson(value, clazz);
        }
    
        public static void remove(String key, int count, Object obj) {
            if (obj == null) {
                return;
            }
    
            redisTemplate.opsForList().remove(key, count, toJson(obj));
        }
    
        /* ----------- zset --------- */
        public static int zcard(String key) {
            return redisTemplate.opsForZSet().zCard(key).intValue();
        }
    
        public static <T> List<T> zrange(String key, long start, long end, Class<T> clazz) {
            Set<String> set = redisTemplate.opsForZSet().range(key, start, end);
            return parseJsonList(setToList(set), clazz);
        }
    
        private static List<String> setToList(Set<String> set) {
            if (set == null) {
                return null;
            }
            return new ArrayList<String>(set);
        }
    
        public static void zadd(String key, Object obj, double score) {
            if (obj == null) {
                return;
            }
            redisTemplate.opsForZSet().add(key, toJson(obj), score);
        }
    
        public static void zaddAll(String key, List<TypedTuple<?>> tupleList, Long timeout, TimeUnit unit) {
            if (tupleList == null || tupleList.isEmpty()) {
                return;
            }
    
            Set<TypedTuple<String>> tupleSet = toTupleSet(tupleList);
            redisTemplate.opsForZSet().add(key, tupleSet);
            if (timeout != null) {
                redisTemplate.expire(key, timeout, unit);
            }
        }
    
        private static Set<TypedTuple<String>> toTupleSet(List<TypedTuple<?>> tupleList) {
            Set<TypedTuple<String>> tupleSet = new LinkedHashSet<TypedTuple<String>>();
            for (TypedTuple<?> t : tupleList) {
                tupleSet.add(new DefaultTypedTuple<String>(toJson(t.getValue()), t.getScore()));
            }
            return tupleSet;
        }
    
        public static void zrem(String key, Object obj) {
            if (obj == null) {
                return;
            }
            redisTemplate.opsForZSet().remove(key, toJson(obj));
        }
    
        public static void unionStore(String destKey, Collection<String> keys, Long timeout, TimeUnit unit) {
            if (keys == null || keys.isEmpty()) {
                return;
            }
    
            Object[] keyArr = keys.toArray();
            String key = (String) keyArr[0];
    
            Collection<String> otherKeys = new ArrayList<String>(keys.size() - 1);
            for (int i = 1; i < keyArr.length; i++) {
                otherKeys.add((String) keyArr[i]);
            }
    
            redisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
            if (timeout != null) {
                redisTemplate.expire(destKey, timeout, unit);
            }
        }
    
        /* ----------- tool methods --------- */
        public static String toJson(Object obj) {
            return JSON.toJSONString(obj, SerializerFeature.SortField);
        }
    
        public static <T> T parseJson(String json, Class<T> clazz) {
            return JSON.parseObject(json, clazz);
        }
    
        public static List<String> toJsonList(Collection<?> values) {
            if (values == null) {
                return null;
            }
    
            List<String> result = new ArrayList<String>();
            for (Object obj : values) {
                result.add(toJson(obj));
            }
            return result;
        }
    
        public static <T> List<T> parseJsonList(List<String> list, Class<T> clazz) {
            if (list == null) {
                return null;
            }
    
            List<T> result = new ArrayList<T>();
            for (String s : list) {
                result.add(parseJson(s, clazz));
            }
            return result;
        }
    }

    又一版本:

    @Component
    public class RedisCache {
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        public RedisCache() {
        }
    
        public RedisTemplate<String, Object> getRedisTemplate() {
            return this.redisTemplate;
        }
    
        public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        public Object get(Object key) {
            final String keyf = key.toString();
            Object object = null;
            object = this.redisTemplate.execute(new RedisCallback<Object>() {
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] key = keyf.getBytes();
                    byte[] value = connection.get(key);
                    return value == null ? null : RedisCache.this.toObject(value);
                }
            });
            return object;
        }
    
        public void put(Object key, final Object value, final long liveTime) {
            final String keyf = key.toString();
            this.redisTemplate.execute(new RedisCallback<Long>() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] keyb = keyf.getBytes();
                    byte[] valueb = RedisCache.this.toByteArray(value);
                    connection.set(keyb, valueb);
                    if (liveTime > 0L) {
                        connection.expire(keyb, liveTime);
                    }
    
                    return 1L;
                }
            });
        }
    
        private byte[] toByteArray(Object obj) {
            byte[] bytes = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
            try {
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(obj);
                oos.flush();
                bytes = bos.toByteArray();
                oos.close();
                bos.close();
            } catch (IOException var5) {
                var5.printStackTrace();
            }
    
            return bytes;
        }
    
        private Object toObject(byte[] bytes) {
            Object obj = null;
    
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
                obj = ois.readObject();
                ois.close();
                bis.close();
            } catch (IOException var5) {
                var5.printStackTrace();
            } catch (ClassNotFoundException var6) {
                var6.printStackTrace();
            }
    
            return obj;
        }
    
        public void del(Object key) {
            final String keyf = key.toString();
            this.redisTemplate.execute(new RedisCallback<Long>() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.del(new byte[][]{keyf.getBytes()});
                }
            });
        }
    
        public void exprie(Object key, final long liveTime) {
            final String keyf = key.toString();
            this.redisTemplate.execute(new RedisCallback<Boolean>() {
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.expire(keyf.getBytes(), liveTime);
                }
            });
        }
    
        public Boolean exist(Object key) {
            final String keyf = key.toString();
            return (Boolean)this.redisTemplate.execute(new RedisCallback<Boolean>() {
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.exists(keyf.getBytes());
                }
            });
        }
    
        public void clear() {
            this.redisTemplate.execute(new RedisCallback<String>() {
                public String doInRedis(RedisConnection connection) throws DataAccessException {
                    connection.flushDb();
                    return "ok";
                }
            });
        }
    
        public Long incr(Object key) {
            final String keyf = key.toString();
            return (Long)this.redisTemplate.execute(new RedisCallback<Long>() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.incr(keyf.getBytes());
                }
            });
        }
    
        public Long decr(Object key) {
            final String keyf = key.toString();
            return (Long)this.redisTemplate.execute(new RedisCallback<Long>() {
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.decr(keyf.getBytes());
                }
            });
        }
    
        public Set<String> keys(String key) {
            Set<String> keys = this.redisTemplate.keys(key);
            return keys;
        }
    }

    https://blog.csdn.net/plei_yue/article/details/79362372

    https://www.cnblogs.com/gdpuzxs/p/7222309.html

    https://zhuanlan.zhihu.com/p/29195530

    https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.data.redis.serializer.StringRedisSerializer

  • 相关阅读:
    php多态
    二分查找法
    mysql联合索引详解
    PHPFastCGI进程管理器PHP-FPM详解
    IDEA Spark程序报错处理
    逻辑回归与多项逻辑回归
    特征选择--->卡方选择器
    特征变化--->特征向量中部分特征到类别索引的转换(VectorIndexer)
    特征变化--->标签到向量的转换(OneHotEncoder)
    特征变化--->索引到标签的转换(IndexToString)
  • 原文地址:https://www.cnblogs.com/hongdada/p/9141125.html
Copyright © 2011-2022 走看看