SpringBoot整合Redis实现自动缓存、更新、删除
阅读原文时间:2021年04月20日阅读:1

1:引入springboot redis的maven依赖(建议使用spring-boot-dependencies或者使用spring-io-platform进行构建项目)

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

2:配置RedisConfig

/**
 * @author liuenyuan
 **/
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig extends CachingConfigurerSupport {

    @Autowired
    private RedisProperties redisProperties;

    /**
     * redis cache name
     **/
    public static final String REDIS_CACHE_NAME = "epc";

    /**
     * {@link org.springframework.cache.annotation.Cacheable}第一个注解代表从缓存中查询指定的key,如果有,从缓存中取,不再执行方法.如果没有则执
     * 行方法,并且将方法的返回值和指定的key关联起来,放入到缓存中.<br/>
     * {@link org.springframework.cache.annotation.CacheEvict}从缓存中清除指定的key对应的数据.<br/>
     * {@link org.springframework.cache.annotation.CachePut}在新增或者更新的时候,进行使用;更新时,则会覆盖原先的数据<br/>
     * {@link com.adc.da.main.util.RedisService}是使用示例
     *
     * @see org.springframework.cache.annotation.CacheEvict
     * @see org.springframework.cache.annotation.Cacheable
     * @see org.springframework.cache.annotation.CachePut
     * @see com.adc.da.main.util.RedisService
     **/
    @Bean
    public CacheManager cacheManager(@Autowired RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        //0表示永不过期
        redisCacheManager.setDefaultExpiration(0);
        return redisCacheManager;
    }

    /**
     * key redis serializer: {@link StringRedisSerializer} and
     * key redis serializer: {@link Jackson2JsonRedisSerializer}
     **/
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //设置Redis的value为json格式,并存储对象信息的序列化类型
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        valueRedisSerializer.setObjectMapper(objectMapper);

        RedisSerializer keyRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(keyRedisSerializer);
        template.setValueSerializer(valueRedisSerializer);
        template.setHashKeySerializer(keyRedisSerializer);
        template.setHashValueSerializer(valueRedisSerializer);
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();

        log.info("redis server host:{},port:{},database:{}",
                redisProperties.getHost(), redisProperties.getPort(), redisProperties.getDatabase());
        return template;
    }
}

3:配置application.properties的redis相关配置

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

4:自动缓存的使用

/**
 * redis use for example
 *
 * @author liuenyuan
 **/
@Service
@CacheConfig(cacheNames = RedisConfig.REDIS_CACHE_NAME)
public class RedisService {

    //#p0,代表第一个参数
    //Cacheable如果缓存没有值,从则执行方法并缓存数据,如果缓存有值,则从缓存中获取值.
    @Cacheable(key = "#p0")
    public BusRefImg findOne(String id) {
        return new BusRefImg(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID());
    }

    //删除,从缓存中删除相关的key-value值
    // 用来标注在需要清除缓存元素的方法或类上
    @CacheEvict(key = "#p0")
    public boolean deleteOne(String id) {
        return true;
    }


    //新增
    //#p0代表第一个参数,其中spring的cache支持Spel表达式
    @CacheEvict(key = "#p0.id")
    public BusRefImg saveOne(BusRefImg busRefImg) {
        return busRefImg;
    }


    //修改
    //执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
    @CachePut(key = "#p0.id")
    public BusRefImg updateOne(BusRefImg busRefImg) {
        return busRefImg;
    }
}

5:具体的spring cache详解的使用链接:
https://blog.csdn.net/chenshun123/article/details/79518812