SpringBoot整合Redis

其实之前维护SSM项目的时候开发秒杀引入redis也有在网上翻天覆地的找整合的法子,Maven整合SSM和Redis,这次用SpringBoot对引入redis,以为只用半天,结果整了快一周,也是醉的不行。
其实SpringBoot只是简单连接Redis做一个读写的话,异常简单,只要两步

1.引入spring-boot-starter-data-redis依赖

        
            org.springframework.boot
            spring-boot-starter-data-redis
        

2.在需要用的的类中使用@Autowired注入RedisTemplate或StringRedisTemplate,使用

redis基础方法

之所以这么简单,因为在RedisAutoConfiguration.class类中SpringBoot默认配置了这两个bean,大佬博客园zeng1994的整合redis中有原理分析,但真实项目中这么用,两点弊端
1.未免太累,代码这么长,加个expire都得写两行,而且取出的时候还得对数据强转等处理
2.使用RedisTemplate写入的数据直接在redis控制台查看时已经是经过JdkSerializationRedisSerializer处理过的跟乱码似的数据(当然可以用StringRedisTemplate,但是那个局限于String,List<对象>格式数据怎么办?转JSON?)
Redis Desktop Manager查看时

针对第一点可以封装个RedisUtil工具类,针对第二点可以自定义redisTemplate的bean方法,并使用符合自己要求的序列化方式(这里可能就是网上那么多整合redis的唯二区别了,手动狗头=__=),Redis 序列化方式StringRedisSerializer、FastJsonRedisSerializer和KryoRedisSerializer,具体的可以挨个搜索看看吧,这里就直接附上我整合使用的亲测可行的实现

1.RedisConfig自定义redisTemplate的bean方法,其中的stringRedisTemplate不用可以不写
package com.myJavaShop.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
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.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@ConditionalOnClass(RedisAutoConfiguration.class)
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

2.redisUtil工具类,基于之前SSM的工具类做了些修改
package com.myJavaShop.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

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

public class RedisUtil {

    private static Logger log = LoggerFactory.getLogger(RedisUtil.class);

    static RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);

    /**
     * 禁止实例化
     */
    private RedisUtil() {

    }

    private static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            String str = obj.toString();
            if ("".equals(str.trim())) {
                return true;
            }
            return false;
        }
        if (obj instanceof List) {
            List list = (List) obj;
            if (list.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Map) {
            Map map = (Map) obj;
            if (map.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Set) {
            Set set = (Set) obj;
            if (set.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Object[]) {
            Object[] objs = (Object[]) obj;
            if (objs.length <= 0) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 判断key值是否存在
     *
     * @param key 缓存的key
     * @return true:存在 false:不存在
     */
    public static boolean hasKey(String key) {
        log.debug(" hasKey key :{}", key);
        try {
            if (isEmpty(key)) {
                return false;
            }
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 匹配符合正则的key
     *
     * @param patternKey
     * @return key的集合
     */
    public static Set keys(String patternKey) {
        log.debug(" keys key :{}", patternKey);
        try {
            if (isEmpty(patternKey)) {
                return Collections.emptySet();
            }
            return redisTemplate.keys(patternKey);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    public static boolean del(String... key) {
        log.debug(" delete key :{}", key.toString());
        try {
            if (isEmpty(key)) {
                return false;
            }
            Set keySet = new HashSet<>();
            for (String str : key) {
                keySet.add(str);
            }
            redisTemplate.delete(keySet);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 删除一组key值
     *
     * @param keys
     * @return true:成功 false:失败
     */
    public static boolean del(Set keys) {
        log.debug(" delete keys :{}", keys.toString());
        try {
            if (isEmpty(keys)) {
                return false;
            }
            redisTemplate.delete(keys);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    public static boolean delPattern(String key) {
        log.debug(" delete Pattern keys :{}", key);
        try {
            if (isEmpty(key)) {
                return false;
            }
            redisTemplate.delete(redisTemplate.keys(key));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 设置过期时间
     *
     * @param key     缓存key
     * @param seconds 过期秒数
     * @return true:成功 false:失败
     */
    public static boolean setExp(String key, long seconds) {
        log.debug(" setExp key :{}, seconds: {}", key, seconds);
        try {
            if (isEmpty(key)) {
                return false;
            }
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 查询过期时间
     *
     * @param key 缓存key
     * @return 秒数
     */
    public static Long getExpire(String key) {
        log.debug(" getExpire key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0L;
            }

            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0L;
    }

    /**
     * 去的缓存中的最大值并+1
     *
     * @param key 缓存key值
     * @return long    缓存中的最大值+1
     */
    public static long incr(String key) {
        log.debug(" incr key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0;
            }

            return redisTemplate.opsForValue().increment(key, 1);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    public static  boolean set(String key, T obj) {
        log.debug(" set key :{}, value:{}", key, obj);
        try {
            if (isEmpty(key) || isEmpty(obj)) {
                return false;
            }

            redisTemplate.opsForValue().set(key, obj);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    public static  boolean set(String key, T obj, long seconds) {
        log.debug(" set key :{}, value:{}, seconds:{}", key, obj, seconds);
        try {
            if (isEmpty(key) || isEmpty(obj)) {
                return false;
            }

            redisTemplate.opsForValue().set(key, obj);
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中存储的序列化对象
     *
     * @param key 缓存key
     * @return   序列化对象
     */
    public static  T get(String key) {
        log.debug(" get key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (T) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 存入Map数组
     *
     * @param 
     * @param key 缓存key
     * @param map 缓存map
     * @return true:成功 false:失败
     */
    public static  boolean setMap(String key, Map map) {
        log.debug(" setMap key :{}, value: {}", key, map);
        try {
            if (isEmpty(key) || isEmpty(map)) {
                return false;
            }

            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 存入Map数组
     *
     * @param 
     * @param key     缓存key
     * @param map     缓存map
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    public static  boolean setMap(String key, Map map, long seconds) {
        log.debug(" setMap key :{}, value: {}, seconds:{}", key, map, seconds);
        try {
            if (isEmpty(key) || isEmpty(map)) {
                return false;
            }

            redisTemplate.opsForHash().putAll(key, map);
            redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * map中加入新的key
     *
     * @param 
     * @param key     缓存key
     * @param hashKey map的Key值
     * @param value   map的value值
     * @return true:成功 false:失败
     */
    public static  boolean addMap(String key, E hashKey, T value) {
        log.debug(" addMap key :{}, hashKey: {}, value:{}", key, hashKey, value);
        try {
            if (isEmpty(key) || isEmpty(hashKey) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForHash().put(key, hashKey, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存的map
     *
     * @param key 缓存key
     * @return map    缓存的map
     */
    @SuppressWarnings("rawtypes")
    public static Map getMap(String key) {
        log.debug(" getMap key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 查询缓存的map的集合大小
     *
     * @param key 缓存key
     * @return int    缓存map的集合大小
     */
    public static long getMapSize(String key) {
        log.debug(" getMap key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0;
            }

            return redisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0;
    }


    /**
     * 根据key以及hashKey取出对应的Object对象
     *
     * @param key   缓存key
     * @param field 对应map的key
     * @return object    map中的对象
     */
    public static  T getMapKey(String key, String field) {
        log.debug(" getMapkey key :{}, field:{}", key, field);
        try {
            if (isEmpty(key) || isEmpty(field)) {
                return null;
            }

            return (T) redisTemplate.opsForHash().get(key, field);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 取出缓存中map的所有key值
     *
     * @param key 缓存key
     * @return Set map的key值合集
     */
    public static  Set getMapKeys(String key) {
        log.debug(" getMapKeys key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (Set) redisTemplate.opsForHash().keys(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除map中指定的key值
     *
     * @param key   缓存key
     * @param field map中指定的hashKey
     * @return true:成功 false:失败
     */
    public static boolean delMapKey(String key, String field) {
        log.debug(" delMapKey key :{}, field:{}", key, field);
        try {
            if (isEmpty(key) || isEmpty(field)) {
                return false;
            }

            redisTemplate.opsForHash().delete(key, field);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }


    /**
     * 缓存存入List
     *
     * @param 
     * @param key  缓存key
     * @param list 缓存List
     * @return true:成功 false:失败
     */
    public static  boolean setList(String key, List list) {
        log.debug(" setList key :{}, list: {}", key, list);
        try {
            if (isEmpty(key) || isEmpty(list)) {
                return false;
            }

            redisTemplate.opsForList().leftPushAll(key, list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入List
     *
     * @param 
     * @param key     缓存key
     * @param list    缓存List
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    public static  boolean setList(String key, List list, long seconds) {
        log.debug(" setList key :{}, value:{}, seconds:{}", key, list, seconds);
        try {
            if (isEmpty(key) || isEmpty(list)) {
                return false;
            }

            redisTemplate.opsForList().leftPushAll(key, list);
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * Object存入List右侧
     *
     * @param key   缓存key
     * @param value List中的值
     * @return true:成功 false:失败
     */
    public static  boolean addList(String key, T value) {
        log.debug(" addList key :{}, value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key值取出对应的list合集
     *
     * @param key 缓存key
     * @return List 缓存中对应的list合集
     */
    public static  List getList(String key) {
        log.debug(" getList key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (List) redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除并取出list左侧第一个元素
     *
     * @param key
     * @return
     */
    public static  T lpopList(String key) {
        log.debug(" lpopList key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (T) redisTemplate.opsForList().leftPop(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 根据key值截取对应的list合集
     *
     * @param key   缓存key
     * @param start 开始位置
     * @param end   结束位置
     * @return
     */
    public static void trimList(String key, int start, int end) {
        log.debug(" trimList key :{}", key);
        try {
            if (isEmpty(key)) {
                return;
            }

            redisTemplate.opsForList().trim(key, start, end);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 取出list合集中指定位置的对象
     *
     * @param key   缓存key
     * @param index 索引位置
     * @return Object    list指定索引位置的对象
     */
    public static  T getIndexList(String key, int index) {
        log.debug(" getIndexList key :{}, index:{}", key, index);
        try {
            if (isEmpty(key) || index < 0) {
                return null;
            }

            return (T) redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 查询缓存的list的集合大小
     *
     * @param key 缓存key
     * @return int    缓存list的集合大小
     */
    public static long getListSize(String key) {
        log.debug(" getListSize key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0;
            }

            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0;
    }

    /**
     * set集合存入缓存
     * @param 
     * @param key   缓存key
     * @param set   缓存set集合
     * @return  true:成功
     *      false:失败
     */
    public static  boolean setSet(String key, Set set) {
        log.debug(" setSet key :{}, value:{}", key, set);
        try {
            if (isEmpty(key) || isEmpty(set)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, set.toArray());
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合存入缓存
     * @param 
     * @param key   缓存key
     * @param set   缓存set集合
     * @param seconds   秒数
     * @return  true:成功
     *      false:失败
     */
    public static  boolean setSet(String key, Set set, long seconds) {
        log.debug(" setSet key :{}, value:{}, seconds:{}", key, set, seconds);
        try {
            if (isEmpty(key) || isEmpty(set)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, set.toArray());
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合中增加value
     *
     * @param key   缓存key
     * @param value 增加的value
     * @return true:成功 false:失败
     */
    public static boolean addSet(String key, Object value) {
        log.debug(" addSet key :{}, value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中对应的set合集
     *
     * @param 
     * @param key 缓存key
     * @return Set 缓存中的set合集
     */
    public static  Set getSet(String key) {
        log.debug(" getSet key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (Set) redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 判断set中是否包含成员
     *
     * @param key    集合
     * @param member 成员
     * @return
     */
    public static boolean isMemSet(String key, String member) {
        log.debug(" isMemSet key :{},member :{}", key, member);
        try {
            if (isEmpty(key) || isEmpty(member)) {
                return false;
            }
            return redisTemplate.opsForSet().isMember(key, member);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 有序集合存入数值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @param score 评分
     * @return
     */
    public static boolean addZSet(String key, Object value, double score) {
        log.debug(" addZSet key :{},value:{}, score:{}", key, value, score);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            return redisTemplate.opsForZSet().add(key, value, score);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @return
     */
    public static boolean removeZSet(String key, Object value) {
        log.debug(" removeZSet key :{},value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForZSet().remove(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    public static boolean removeRangeZSet(String key, long start, long end) {
        log.debug(" removeZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isEmpty(key)) {
                return false;
            }

            redisTemplate.opsForZSet().removeRange(key, start, end);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中获取指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    public static  Set getZSet(String key, long start, long end) {
        log.debug(" getZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isEmpty(key)) {
                return Collections.emptySet();
            }

            return (Set) redisTemplate.opsForZSet().range(key, start, end);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }
}
 
 
3.至于将工具类和bean方法连接在一起的SpringUtil,可以参考Maven整合SSM和Redis中的CacheContextUtil.java,网上也多的是,就不赘叙了,以下是Set<对象>实现效果
这才是常规的实现思路嘛

你可能感兴趣的:(SpringBoot整合Redis)