springboot使用redis作缓存

总结下我在springboot中搭建redis缓存的过程。

  • 在pom.xml中添加redis依赖:

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

  • 在application.properties中添加redis的配置:
# 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
  • 配置redis缓存,新建RedisCacheConfig.java:
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    @Bean
    @Override
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName()+":");
                sb.append(method.getName());
                if (params!=null&¶ms.length>0){
                    sb.append(":");
                }
                boolean isF=true;
                for (Object obj : params) {
                    if (isF){
                        sb.append(obj.toString());
                        isF=false;
                    }else {
                        sb.append("&"+obj.toString());
                    }
                }
                return sb.toString();
            }
        };

    }

    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisSerializer keySerializer=new StringRedisSerializer();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        return cacheManager;
    }

    @Bean
    public RedisTemplate SRT(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        //定义key序列化方式
        RedisSerializer redisSerializer = new StringRedisSerializer();
        //定义value的序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setKeySerializer(redisSerializer);
        template.setHashKeySerializer(redisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

说明:
1.public KeyGenerator keyGenerator():该方法是自定义key值生成规则的方法。
2.cacheManager:方法中

RedisSerializer keySerializer=new StringRedisSerializer();
redisTemplate.setKeySerializer(keySerializer);
redisTemplate.setHashKeySerializer(keySerializer);

用来指定key值序列化规则,这里采用了StringRedisSerializer作为序列化,有效的避免了类似 \xac\xed\x00\x05t\x00\tb 这种开头的key值。

  • 使用缓存:
    //缓存
    @Cacheable(value = "test")
    public Object putCache(Object param){
        //...
    }
    //清除缓存
    @CacheEvict(value = "test",allEntries = true)
    public void clearCache(){
        //...
    }
`allEntries = true` 代表`value = "test"`的缓存全部被清除

你可能感兴趣的:(springboot使用redis作缓存)