springboot集成redis缓存,使用注解

所有文章只是记录工作中用到的一些东西,方便日后自己在别的项目中快速上手,下面开始springboot和redis的整合。

1.引入依赖

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

2.配置aplication.yml

spring:
  redis:
    host: 192.168.1.8
    password: xSjXY^0,GQeJ4*35

3.编写RedisConfig类

@Configuration
@EnableCaching//开启注解
public class RedisConfig {
    /**
     *  配置redisTemplate,主要指定key和value的序列化方式
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Object, Object> template=new RedisTemplate<Object, Object>();
        template.setConnectionFactory(connectionFactory);
        //实现序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        //实现序列化和反序列化redis的value值,默认使用JdkSerializationRedisSerializer
        //template.setValueSerializer(new RedisObjectSerializer());
        //template.setValueSerializer();
        return template;
    }

    /**
     * 配置缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        /**
         * 指定缓存的名称
         */
        cacheManager.setCacheNames(Arrays.asList("cars","series","models"));
        cacheManager.setUsePrefix(true);
        /**
         * 设置过期时间
         */
        cacheManager.setDefaultExpiration(1800L);
        return cacheManager;
    }

    /**
     * key生成策略
     * */
    @Bean
    public KeyGenerator accountKeyGenerator() {
        return new KeyGenerator(){
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return target.getClass().toString() ;
            }
        };
    }
}

4.在service中使用注解进行缓存

@Override
    @Cacheable(value = "cars" , keyGenerator  = "accountKeyGenerator")
    public JsonResult carBrands() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("auth", DigestUtils.md5Hex(appKey+":"+secret));
        HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders);
        JsonResult body = restTemplate.exchange(remoteServiceHost + "/foo",
                HttpMethod.POST, entity, JsonResult.class).getBody();
        System.out.println(" remote from ");
        return body;
    }

    @Override
    @Cacheable(value = "series" , key = "'series'+#id")
    public JsonResult findCarSeries(Integer id) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("auth", DigestUtils.md5Hex(appKey+":"+secret));
        HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders);
        JsonResult body = restTemplate.exchange(remoteServiceHost + "/foo?brandsId="+id,
                HttpMethod.GET, entity, JsonResult.class).getBody();
        System.out.println(" remote from ");
        return body;
    }

    @Override
    @Cacheable(value = "models" ,key = "'models'+#id")
    public JsonResult findCarModels(Integer id) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("auth", DigestUtils.md5Hex(appKey+":"+secret));
        HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders);
        JsonResult body = restTemplate.exchange(remoteServiceHost + "foo?seriesId="+id,
                HttpMethod.GET, entity, JsonResult.class).getBody();
        System.out.println(" remote from ");
        return body;
    }

springboot整合redis常用的一些注解

  1. @Cacheable
    可作用于方法或类上,用在类上所有方法起作用。该注解主要用于缓存执行后的结果。@Cacheable可以指定三个属性,value、key、conditionvalue用于指定作用的缓存对象名称,可以为多个,key指定缓存的建,可以取方法的参数。
    @Cacheable(value="users", key="#id")
    public User find(Integer id) {
    }

    @Cacheable(value="users", key="#p0")
    public User find(Integer id) {
    }

    @Cacheable(value="users", key="#user.id")
    public User find(User user) {
    }

    @Cacheable(value="users", key="#p0.id")
    public User find(User user) {
    }

condition属性指定发生的条件
有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。如下示例表示只有当user的id为偶数时才会进行缓存

    @Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
    public User find(User user) {
        return user;
    }

2.@CachePut
在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中

@CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中
   public User find(Integer id) {
}

3.@CacheEvict
@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。
allEntries属性
allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

 @CacheEvict(value="users", allEntries=true)
   public void delete(Integer id) 
   }

beforeInvocation属性
清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。

@CacheEvict(value="users", beforeInvocation=true)
   public void delete(Integer id) {
   }

猜你喜欢

转载自blog.csdn.net/qq_34322005/article/details/82629126