Springboot2.0 + redis 实现 cache

Spring针对不同的缓存技术,需要实现不同的cacheManager,
Spring定义了如下的cacheManger实现。

Springboot2.0 + redis 实现 cache_第1张图片

在这里我用的是rediscache, 主要存储机场表和航班表。
在其中看了很多博客, 最后贴一份可用的redis 配置

1. 引入依赖

  
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-cacheartifactId>
        dependency>

2.配置yml

redis:
        host: 127.0.0.1
        password :
        port: 6379
        timeout: 60s
        jedis:
          pool:
            max-idle: 500  # 最大空闲连接数
            min-idle: 50   # 最小空闲连接数
            max-wait:  -1s # 等待可用连接的最大时间,负数为不限制
            max-active: -1 # 最大活跃连接数,负数为不限制

3.Java代码配置RedisCache

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
    @Bean(name = "redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(stringSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(stringSerializer);
        template.setConnectionFactory(factory);
        return template;
    }


    @Bean
    /* cache key generation strategy */
    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());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    /*  redis-cache configuration */
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        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);

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 7 天缓存过期
                .entryTtl(Duration.ofDays(7))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

4.@Cacheable 注解写入缓存

 @Override
    @Cacheable(value = "cache:airport", key = "#code")
    public AirportBO getByCode(String code) {
        return airportMapper.getByCode(code);
    }

key 最好选取唯一的。
Springboot2.0 + redis 实现 cache_第2张图片

如果需要修改缓存,则需要使用@CachePut,
删除缓存:@CacheEvict

注意存储到redis 的POJO需要实现序列化接口

你可能感兴趣的:(javaweb知识)