spring增加缓存最简单的方法

添加配置信息

(1).config/config.properties文件中添加

  1. #缓存默认有效期1h (60 * 60 = 3600秒)
  2. redis.expiration=3600
  3. #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
  4. redis.maxIdle=300
  5. #连接池的最大数据库连接数。设为0表示无限制。
  6. #Redis默认允许客户端连接的最大数量是10000。若是看到连接数超过5000以上,那可能会影响Redis的性能。倘若一些或大部分客户端发送大量的命令过来,这个数字会低的多。
  7. redis.maxActive=5000
  8. #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
  9. redis.maxWait=-1
  10. #申请连接时检测连接是否有效,配置true会降低性能,但是可以检测链接有效性,默认false
  11. redis.testOnBorrow=true
  12. #返回前会先校验这个链接有效性,如果无效会被销毁,默认值false
  13. redis.testOnReturn=true
  14. redis.database=0
  15. #缓存时间范围
  16. cache.cacheTime=300,400
  17. #同步等待时间
  18. cache.syncWaitTime=300
  19. #空值缓存时间
  20. cache.nullCacheTime=60

(2).config文件夹下添加spring-data-redis.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.  xmlns:context="http://www.springframework.org/schema/context"
  5.  xmlns:cache="http://www.springframework.org/schema/cache"
  6.  xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.3.xsd
  10. http://www.springframework.org/schema/cache
  11. http://www.springframework.org/schema/cache/spring-cache-4.3.xsd">
  12.  <description>Jedis Configuration</description>
  13.  <!-- 加载配置属性文件 -->
  14.  <context:property-placeholder ignore-unresolvable="true" location="classpath:config/config.properties"/>
  15.  <!-- ******************** redis缓存 **********************-->
  16.  <!-- 启用缓存注解功能,否则注解不会生效 -->
  17.  <cache:annotation-driven cache-manager="cacheManager" />
  18.  <!-- redis 相关配置 -->
  19.  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  20.  <property name="maxIdle" value="${redis.maxIdle}" />
  21.  <property name="maxWaitMillis" value="${redis.maxWait}" />
  22.  <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  23.  <property name="testOnReturn" value="${redis.testOnReturn}" />
  24.  </bean>
  25.  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
  26.  p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"
  27.  p:database="${redis.database}" p:timeout="${redis.timeout}"
  28.  p:pool-config-ref="poolConfig" />
  29.  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  30.  <property name="connectionFactory" ref="jedisConnectionFactory" />
  31.  <!--对key的序列化器 -->
  32.  <property name="keySerializer">
  33.  <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  34.  </property>
  35.  <!--是对value的列化器 默认:JdkSerializationRedisSerializer -->
  36.  <property name="valueSerializer">
  37.  <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
  38.  </property>
  39.  </bean>
  40.  <!-- 扩展RedisCacheManager -->
  41.  <bean id="cacheManager" class="com.we.core.web.cache.TFRedisCacheManager">
  42.  <constructor-arg ref="redisTemplate" />
  43.  <!-- 是否使用前缀 默认: -->
  44.  <!--<property name="usePrefix" value="true" />-->
  45.  <!-- 默认有效期1h (60 * 60 = 3600秒) -->
  46.  <property name="defaultExpiration" value="${redis.expiration}" />
  47.  </bean>
  48.  <!-- ******************** redis缓存 **********************-->
  49. </beans>

(3).config/spring-context.xml中添加

  1. <import resource="spring-data-redis.xml" />

注解使用

概况

基于注解的缓存声明,需要掌握的有:@Cacheable@CachePut 、 @CacheEvict 和@Caching

以下列举了几种常用的使用属性,详情可自行查阅

  1. @Cacheable(value="",condition="",key="",unless="")
  2.  public @interface Cacheable{ 
  3.  String[] value(); //缓存的名字,可以把数据写到多个缓存,我们扩展了属性:area#60*10, area是value,60*10是缓存时间(单位秒),不加走默认(1h)
  4.  String key() default ""; //缓存key,如果不指定将使用默认的KeyGenerator生成,后边介绍
  5.  String condition() default ""; //满足缓存条件的数据才会放入缓存,condition在调用方法之前和之后都会判断
  6.  String unless() default ""; //用于否决缓存更新的,不像condition,该表达只在方法执行之后判断,此时可以拿到返回值result进行判断了
  7.  String keyGenerator() default ""; //指定key规则
  8. } 
  9. @CachePut(value="",condition="",key="",unless="")
  10.  public @interface CachePut { 
  11.  String[] value(); //缓存的名字,可以把数据写到多个缓存
  12.  String key() default ""; //缓存key,如果不指定将使用默认的KeyGenerator生成,后边介绍
  13.  String condition() default ""; //满足缓存条件的数据才会放入缓存,condition在调用方法之前和之后都会判断
  14.  String unless() default ""; //用于否决缓存更新的,不像condition,该表达只在方法执行之后判断,此时可以拿到返回值result进行判断了
  15. } 
  16. @Cacheable(value="",condition="",key="",unless="")
  17.  public @interface CacheEvict { 
  18.  String[] value(); //缓存的名字,可以把数据写到多个缓存
  19.  String key() default ""; //缓存key,如果不指定将使用默认的KeyGenerator生成,后边介绍
  20.  String condition() default ""; //满足缓存条件的数据才会放入缓存,condition在调用方法之前和之后都会判断
  21.  boolean allEntries() default false; //是否移除所有数据
  22.  boolean beforeInvocation() default false;//是调用方法之前移除/还是调用之后移除
  23. @Caching(value="",condition="",key="",unless="")
  24. public @interface Caching {
  25.  Cacheable[] cacheable() default {}; //从缓存获取多个,如果没有则执行方法体,获取值后加入缓存
  26.  CachePut[] put() default {}; //缓存多个
  27.  CacheEvict[] evict() default {}; //从缓存移除多个
  28. }

@Cacheable

较常用,用在查询方法上,先从缓存中读取,如果缓存不存在再调用该方法获取数据,然后把返回的数据添加到缓存中去

正如其名字,@Cacheable用于添加在需高速缓存的方法上。这些方法默认会以参数为主键把返回结果存储到高速缓存中,以便在随后的调用(使用相同的参数)方法,直接返回高速缓存中的值,不需要实际执行此方法。

  • 最简单的方式,只需要声明一个相关缓存策略的名称

    1. @Cacheable("area#60*10")
    2. public Book getAreaVersion4(String code) {...}
  • 也可以设置多个缓冲块,其中一个缓冲块命中即会返回,并会同步其他缓存块:

    1. @Cacheable(value = {"area#60*10","city#60*30"})
    2. public Book getAreaVersion4(String code) {...}
  • 定制key,且加同步

    1. @Cacheable(value = {"area#60*10"}, key = "'code:'+#code",sync = true)
    2.  public AreaDto getAreaVersion4(String code) {
    3.  return areaBaseService.get (code);
    4.  }
  • 定制key,且加同步,加条件

    1. @Cacheable(value = {"area#60*10"}, key = "'code:'+#code",sync = true, condition = "#code=='100000'")
    2.  public AreaDto getAreaVersion4(String code) {
    3.  return areaBaseService.get (code);
    4.  }

@CacheEvict

主要对方法配置,用来标记要清空缓存的方法,当这个方法被调用并满足一定条件后,即会清空缓存。

  • 参数解析:

value:缓存的位置,不能为空。
key:缓存的key,默认为空。
condition:触发的条件,只有满足条件的情况才会清楚缓存,默认为空,支持SpEL。
allEntries:true表示清除value中的全部缓存,默认为false。

  1. /**
  2. * 情况area#60*10下所有缓存
  3. */
  4. @CacheEvict(value = {"area#60*10"}, key = "'code:'+#code", condition = "#code=='100000'")
  5.  public AreaDto delete(String code) {
  6.  return areaBaseService.delete (code);
  7.  }
  1.  /**
  2. * 只要执行了delArea2方法,就刷新缓存名为”getAreaVersion4”下面的所有缓存
  3. */
  4.  @Caching(evict = {@CacheEvict(value = {"getAreaVersion4#60*5"}, allEntries = true)})
  5.  public void delArea2() {
  6.  }

@CachePut

主要针对方法的配置,能够根据方法的请求参数对其结果进行缓存,和@Cacheable不同的是,它每次都会触发真实方法的调用。

  1. @CachePut(value = {"area#60*10"}, key = "'code:'+#code",sync = true, condition = "#code=='100000'")
  2.  public AreaDto getAreaVersion4(String code) {
  3.  return areaBaseService.get (code);
  4.  }

其他自行查阅

  1. spring-data-redis

自定义缓存注解

1.更新项目包

  • we-core-web

2.添加默认配置

  • 在apollo中添加 或者 在config/config.properties中添加

    优先级顺序:1、apollo;2、配置文件;

    1. #缓存时间范围
    2. cache.cacheTime=300,400
    3. #同步等待时间
    4. cache.syncWaitTime=3
    5. #空值缓存时间
    6. cache.nullCacheTime=60

3.应用

    • 使用demo

      1.  /**
      2. * 目标方法
      3. * <p&
      4. * 支持限流
      5. * 支持穿透
      6. * 支持异步处理
      7. * </p&
      8. *
      9. * @param code
      10. * @return
      11. */
      12.  @TFCacheable(groupName = CACHE_GROUP_NAME, cacheTime = {300, 400}, syncWaitTime = 300)
      13.  public AreaDto getXXX(String code) {
      14.  return xxxBaseService.get (code);
      15.  }

注解介绍

  1.  /**
  2. * 分组名
  3. */
  4.  String groupName() default "";
  5.  /**
  6. * 缓存的时间范围
  7. * <br/&
  8. * 过期时间,单位为秒
  9. *
  10. * <p&
  11. * 格式:minTime-maxTime,如:60-120
  12. * </p&
  13. */
  14.  int[] cacheTime() default 0;
  15.  /**
  16. * 是否同步
  17. * 同步排队时间:{@link #syncWaitTime}.
  18. * <p&
  19. * 细粒度同步锁,锁定级别:参数级别
  20. * </p&
  21. * @see #syncWaitTime
  22. */
  23.  boolean sync() default true;
  24.  /**
  25. * 同步等待时间
  26. * <br/&
  27. * 过期时间,单位为秒
  28. *
  29. * <p&
  30. * 过期时间,单位为秒
  31. * 如果开启同步,默认排队时间,超过后,抛超时异常
  32. * </p&
  33. * @see #sync
  34. */
  35.  int syncWaitTime() default 0;
  36.  /**
  37. * 空值缓存时间
  38. *
  39. * <p&
  40. * 空值会缓存短暂的时间,防止方法请求不断请求数据库,减少穿透几率
  41. * </p&
  42. */
  43.  int nullCacheTime() default 0
示例
@Cacheable(value = "ActivityScopeRedis#60*60",key = "#root.methodName + #activityId")
    public List<ActivityScopeDto> findByActivityId(long activityId) {
        return activityScopeBaseDao.findByActivityId(activityId);
    }

猜你喜欢

转载自www.cnblogs.com/houpengwei/p/10973955.html