redis(八)之springboot整合redis缓存注解@Cacheable、@CacheEvict、@CachePut

@Cacheable:

主要用来配置方法,能够根据方法的请求参数对其结果进行缓存。即当重复使用相同参数调用方法的时候,方法本身不会被调用执行,即方法本身被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。
参数:
value:缓存的名字,必须指定至少一个。
key:缓存的key,可以为空,如果指定要按照SpEL表达式编写;如果不指定,则缺省按照方法的所有参数进行组合。
condition:缓存的条件,可以为空,使用SpEL编写,返回true或者false,只有为true才能缓存。

@CachePut:

这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,用于更新缓存与数据库。
参数同上。

@CacheEvict

删除缓存。
参数:allEntries:true表示清除value中的全部缓存,默认为false。其余参数同上

1.pom.xml依赖

 	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
	</dependency>

2.RedisConfig


@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
    //自定义key
    @Bean
    public KeyGenerator simpleKeyGenerator() {
        return (o, method, objects) -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getSimpleName());
            stringBuilder.append(".");
            stringBuilder.append(method.getName());
            stringBuilder.append("[");
            for (Object obj : objects) {
                stringBuilder.append(obj.toString());
            }
            stringBuilder.append("]");

            return stringBuilder.toString();
        };
    }
    //默认缓存时间
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl(60), // 默认策略,未配置的 key 会使用这个
                this.getRedisCacheConfigurationMap() // 指定 key 策略
        );
    }
    //自定义缓存时间
    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
    /*    redisCacheConfigurationMap.put("SelectMax_T", this.getRedisCacheConfigurationWithTtl(30));*/
        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> 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 redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }

}

3.使用

 @Override
    @CachePut(value = "Max_T",key="'CropId:'+#p0")
    public double UpdateMax_T(int CropId,double Max_T) {
        List list=parameterMapper.selectByExample(null);
        for(Object parameter_:list){
            Parameter parameter=(Parameter) parameter_;
            if(parameter.getCropId()==CropId){
               parameter.setMaxT(Max_T);
               parameterMapper.updateByExample(parameter, new ParameterExample());
            }
        }
        return Max_T;
    }

    @Override
    @Cacheable(value = "Max_T",key="'CropId:'+#p0")
    public double SelectMax_T(int CropId) {
        Double Max_T=0.0;
        List list=parameterMapper.selectByExample(null);
        for(Object parameter_:list){
            Parameter parameter=(Parameter) parameter_;
            if(parameter.getCropId()==CropId){
                Max_T=parameter.getMaxT();
            }
        }
        return Max_T;
    }

猜你喜欢

转载自blog.csdn.net/qq_40351478/article/details/88762555