SpringBoot集成Redis结合RedisTemplate操作


前言

本文实现了在SpringBoot中集成Redis,使用RedisTemplate对象操作并编写了一些常用方法的工具类。


一、引入依赖

<!-- redis 缓存操作 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 -->
<!-- 使用lettuce客户端需要引入commons-pool2依赖 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

二、基础配置

1、配置application.yml文件

配置如下:

spring:
  # redis 配置
  redis:
    # 地址
    host: 127.0.0.1
    # 端口,默认为6379
    port: 6379
    # 密码,没有不填
    password: ''
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms

2、RedisTemplate配置

代码如下:

/*
*自定义Redis配置类,进行序列化以及RedisTemplate设置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    
    

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
    
    
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        // 使用StringRedisSerializer序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 使用StringRedisSerializer序列化和反序列化redis hash类型的key值
        template.setHashKeySerializer(new StringRedisSerializer());
        // 序列化和反序列化redis hash类型的value值
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

}

3、Jackson2JsonRedisSerializer序列化策略配置

/**
 * Jackson2JsonRedisSerializer序列化策略
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    
    
    private ObjectMapper objectMapper = new ObjectMapper();

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    static
    {
    
    
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJson2JsonRedisSerializer(Class<T> clazz)
    {
    
    
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
    
    
        if (t == null)
        {
    
    
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
    
    
        if (bytes == null || bytes.length <= 0)
        {
    
    
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }

    public void setObjectMapper(ObjectMapper objectMapper)
    {
    
    
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class<?> clazz)
    {
    
    
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

三、工具类

一些常用方法的封装
代码如下:

/**
 * redis缓存工具类
 */
@Component
public class RedisCache {
    
    

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
    
    
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
    
    
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     * 默认【秒】为单位
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
    
    
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     * 【自定义时间单位】
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     *
     *
     *  《TimeUnit详解》
     *    TimeUnit.DAYS //天
     *    TimeUnit.HOURS //小时
     *    TimeUnit.MINUTES //分钟
     *    TimeUnit.SECONDS //秒
     *    TimeUnit.MILLISECONDS //毫秒
     *    TimeUnit.NANOSECONDS //毫微秒
     *    TimeUnit.MICROSECONDS //微秒
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
    
    
        return redisTemplate.expire(key, timeout, unit);
    }

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

    /**
     * 删除单个key
     *
     * @param key
     */
    public boolean deleteKey(final String key)
    {
    
    
        return redisTemplate.delete(key);
    }

    /**
     * 删除多个key
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteKeys(final Collection collection)
    {
    
    
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
    
    
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
    
    
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param value 缓存的数据可以传多个,用,隔开
     *              例如:setCacheSet("key","1","2","3")
     * @return 缓存数据的对象
     */
    public <T> long setCacheSet(final String key, final Object... value)
    {
    
    
        Long count = redisTemplate.opsForSet().add(key, value);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
    
    
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
    
    
        if (dataMap != null) {
    
    
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

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

    /**
     * 获取缓存map的所有key值
     *
     * @param key
     * @return
     */
    public <T> Set<String> getCacheMapKeys(final String key)
    {
    
    
        return redisTemplate.opsForHash().keys(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
    
    
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
    
    
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
    
    
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 模糊查询所有key值
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
    
    
        return redisTemplate.keys(pattern);
    }
}

四、方法实例

基本对象类型

1、缓存基本对象类型

  • 方法示例
//注入自定义封装的工具类
@Autowired
private RedisCache redisCache;


/**
 * 缓存基本对象类型 String、Integer、实体类等.....
 * @return
 */
@PostMapping("/setCacheObject")
@ApiOperation(value ="缓存基本对象")
public String setCacheObject(){
    
    
    //自定义key
    String key = "strKey";
    //自定义value
    String value = "张三";
    //缓存基本对象
    redisCache.setCacheObject(key,value);
    return "SUCCESS!";
}
  • 结果示例
    在这里插入图片描述

2、缓存基本对象并设置过期时间

  • 方法示例
/**
 * 设置过期时间
 * 缓存基本对象类型 String、Integer、实体类等.....
 * @return
 */
@PostMapping("/setCacheObjectByTime")
@ApiOperation(value ="缓存基本对象并设置过期时间")
public String setCacheObjectByTime(){
    
    
    //自定义key
    String key = "strTimeKey";
    //自定义value
    String value = "过期时间value";
    //过期时间
    Integer timeOut = 10;
    //放入缓存,并设置过期时间,单位为秒
    redisCache.setCacheObject(key,value,timeOut, TimeUnit.SECONDS);
    return "SUCCESS!";
}
  • 结果示例
    在这里插入图片描述

3、缓存实体类

  • 方法示例
/**
* 缓存实体类对象
* @return
*/
@PostMapping("/setCacheObjectByEntity")
@ApiOperation(value ="缓存实体类对象")
public String setCacheObjectByEntity(){
    
    
   //自定义key
   String key = "userKey";
   TUser tUser = new TUser();
   tUser.setName("张三");
   tUser.setAge("18");
   //放入缓存
   redisCache.setCacheObject(key,tUser);
   return "SUCCESS!";
}
  • 结果示例
    在这里插入图片描述

4、获取缓存对象

已实体类对象为例

  • 方法示例
/**
 * 获取缓存实体对象 entity
 * @param key:缓存的key值
 * @return TUser
 */
@GetMapping("/getCacheObjectByEntity")
@ApiOperation(value ="获取缓存基本对象 - 实体类")
public TUser getCacheObjectByEntity(String key){
    
    
    //在缓存中获取key值
    TUser tUser = redisCache.getCacheObject(key);
    System.out.println(tUser);
    return tUser;
}
  • 结果示例
    在这里插入图片描述

List类型

1、缓存List类型数据

  • 代码示例
 /**
  *缓存 List 类型
  * @return
  */
 @PostMapping("/setCacheList")
 @ApiOperation(value ="缓存List类型")
 public String setCacheList(){
    
    
     //自定义key值
     String key = "listKey";
     //自定义List数据
     List<String> list = new ArrayList<>();
     list.add("张三");
     list.add("李四");
     //放入缓存
     redisCache.setCacheList(key,list);
     //设置key过期时间,10秒钟过期
//        redisCache.expire(key,10,TimeUnit.SECONDS);
     return "SUCCESS!";
 }
  • 结果示例
    在这里插入图片描述

2、获取缓存Lsit对象

  • 代码示例
/**
 * 获取缓存Lsit对象
 * @param key:缓存的key值
 * @return TUser
 */
@GetMapping("/getCacheList")
@ApiOperation(value ="获取缓存Lsit对象")
public List<String> getCacheList(String key){
    
    
    //在缓存中获取key对应的值
    List<String> cacheList = redisCache.getCacheList(key);
    System.out.println(cacheList);
    return cacheList;
}
  • 结果示例
    在这里插入图片描述

Set类型

1、缓存Set类型数据

  • 代码示例
/**
 * 缓存 Set 类型
 * @return
 */
@PostMapping("/setCacheSet")
@ApiOperation(value ="缓存Set类型")
public String setCacheSet(){
    
    
    //自定义key值
    String key = "setKey";
    //自定义List数据
    TUser u1 = new TUser("张三","18");
    TUser u2 = new TUser("张三","18");
    TUser u3 = new TUser("李四","18");
    //放入缓存
    redisCache.setCacheSet(key,u1,u2,u3);
    //设置key过期时间,10秒钟过期
//        redisCache.expire(key,10,TimeUnit.SECONDS);
    return "SUCCESS!";
}
  • 结果示例
    在这里插入图片描述

2、获取缓存Set对象

  • 代码示例
/**
 * 获取缓存Set对象
 * @param key:缓存的key值
 * @return Set<TUser>
 */
@GetMapping("/getCacheSet")
@ApiOperation(value ="获取缓存Set对象")
public Set<TUser> getCacheSet(String key){
    
    
    //在缓存中获取key对应的值
    Set<TUser> cacheSet = redisCache.getCacheSet(key);
    System.out.println(cacheSet);
    return cacheSet;
}
  • 结果示例
    在这里插入图片描述

Map类型

1、缓存 Map 类型

  • 代码示例
/**
 * 缓存 Map 类型
 * @return
 */
@PostMapping("/setCacheHash")
@ApiOperation(value ="缓存Map类型")
public String setCacheMap(){
    
    
    //自定义key值
    String key = "mapKey";
    //自定义List数据
    Map<String,Object> map = new HashMap<>();
    map.put("name","张三");
    map.put("age",18);
    map.put("sex","男");
    //放入缓存
    redisCache.setCacheMap(key,map);
    return "SUCCESS!";
}
  • 结果示例
    在这里插入图片描述

2、获取缓存Map对象

  • 代码示例
/**
 *获取缓存Map对象
 * @param key:缓存的key值
 */
@GetMapping("/getCacheHash")
@ApiOperation(value ="获取缓存Map对象")
public Map<String, Object> getCacheHash(String key){
    
    
    //在缓存中获取key对应的值
    Map<String, Object> cacheMap = redisCache.getCacheMap(key);
    System.out.println(cacheMap);
    return cacheMap;
}
  • 结果示例
    在这里插入图片描述

3、获取Map中的所有key值

  • 代码示例
/**
 * 获取缓存map的所有key值
 * @return
 */
@GetMapping("/getCacheMapKeys")
@ApiOperation(value ="获取缓存map的所有key值")
public Set<String> getCacheMapKeys(String key){
    
    
    //添加hash数据
    Set<String> mapKey = redisCache.getCacheMapKeys(key);
    System.out.println(mapKey);
    return mapKey;
}
  • 结果示例

在这里插入图片描述

4、获取缓存map的指定key的value

  • 代码示例
/**
 *获取缓存map的指定key的value
 * @param  key:redis的key值
 * @return
 */
@GetMapping("/getMultiCacheMapValue")
@ApiOperation(value ="获取缓存map的指定key的value")
public List<Object> getMultiCacheMapValue(String key){
    
    
    //获取map中key为name和sex 的 value
    Set<Object> hkeys = new HashSet<>();
    hkeys.add("name");
    hkeys.add("sex");
    //添加hash数据
    List<Object> mapValue = redisCache.getMultiCacheMapValue(key, hkeys);
    System.out.println(mapValue);
    return mapValue;
}
  • 结果示例
    在这里插入图片描述

缓存Key值操作

1、模糊查询缓存所有的key

  • 代码示例
/**
 * 模糊查询所有key值
 * 传参例如:
 *    查询所有已Key结尾的key值    *Key
 *    查询所有已Key开头的key值    Key*
 * @return
 */
@GetMapping("/likeKeys")
@ApiOperation(value ="模糊查询所有key值")
public Set<String> likeKeys(String keyName){
    
    
    //添加hash数据
    Set<String> keys = redisCache.keys(keyName);
    System.out.println(keys);
    return keys;
}
  • 结果示例
    所有以Key结尾缓存的key值 参数:*Key
    在这里插入图片描述
    所有以map开头缓存的key值
    在这里插入图片描述

2、删除单个/多个key

  • 代码示例
/**
 * 删除单个/多个key
 * @return
 */
@PostMapping("/deleteObject")
@ApiOperation(value ="删除单个/多个key")
public String deleteObject(@RequestBody List<String> keys){
    
    
    //添加hash数据
    long size = redisCache.deleteKeys(keys);
    return size+"";
}
  • 结果示例
    在这里插入图片描述
    可以看出,listKey跟mapKey已被删除
    在这里插入图片描述

3、设置缓存key的过期时间

  • 代码示例
/**
 * 设置缓存key的过期时间
 * @return
 */
@GetMapping("/setKeyTimout")
@ApiOperation(value ="模糊查询所有key值")
public String setKeyTimout(String key,Integer timeOut){
    
    
    /**
     * key:缓存key值
     * timeOut:过期时间
     * TimeUnit.SECONDS:时间单位(秒)
     */
    redisCache.expire(key,timeOut,TimeUnit.SECONDS);
    return "SUCCESS";
}
  • 结果示例
    请求
    在这里插入图片描述

    效果
    在这里插入图片描述


总结

以上就是在SpringBoot中集成Redis,通过RedisTemplate操作缓存的配置跟方法案例。

猜你喜欢

转载自blog.csdn.net/SmallCat0912/article/details/128422340