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 和@Cachinggit

 

如下列舉了幾種經常使用的使用屬性,詳情可自行查閱github

 

  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

 

較經常使用,用在查詢方法上,先從緩存中讀取,若是緩存不存在再調用該方法獲取數據,而後把返回的數據添加到緩存中去web

 

正如其名字,@Cacheable用於添加在需高速緩存的方法上。這些方法默認會以參數爲主鍵把返回結果存儲到高速緩存中,以便在隨後的調用(使用相同的參數)方法,直接返回高速緩存中的值,不須要實際執行此方法。redis

 

  • 最簡單的方式,只須要聲明一個相關緩存策略的名稱spring

    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,且加同步,加條件less

    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中添加

    優先級順序:一、apollo;二、配置文件;

    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);
    }
相關文章
相關標籤/搜索