添加配置信息
(1).config/config.properties文件中添加
#緩存默認有效期1h (60 * 60 = 3600秒)
redis.expiration=3600
#最大空閑數,數據庫連接的最大空閑時間。超過空閑時間,數據庫連接將被標記為不可用,然后被釋放。設為0表示無限制。
redis.maxIdle=300
#連接池的最大數據庫連接數。設為0表示無限制。
#Redis默認允許客戶端連接的最大數量是10000。若是看到連接數超過5000以上,那可能會影響Redis的性能。倘若一些或大部分客戶端發送大量的命令過來,這個數字會低的多。
redis.maxActive=5000
#最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。
redis.maxWait=-1
#申請連接時檢測連接是否有效,配置true會降低性能,但是可以檢測鏈接有效性,默認false
redis.testOnBorrow=true
#返回前會先校驗這個鏈接有效性,如果無效會被銷毀,默認值false
redis.testOnReturn=true
redis.database=0
#緩存時間范圍
cache.cacheTime=300,400
#同步等待時間
cache.syncWaitTime=300
#空值緩存時間
cache.nullCacheTime=60
(2).config文件夾下添加spring-data-redis.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.3.xsd">
<description>Jedis Configuration</description>
<!-- 加載配置屬性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config/config.properties"/>
<!-- ******************** redis緩存 **********************-->
<!-- 啟用緩存注解功能,否則注解不會生效 -->
<cache:annotation-driven cache-manager="cacheManager" />
<!-- redis 相關配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="testOnReturn" value="${redis.testOnReturn}" />
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"
p:database="${redis.database}" p:timeout="${redis.timeout}"
p:pool-config-ref="poolConfig" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<!--對key的序列化器 -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<!--是對value的列化器 默認:JdkSerializationRedisSerializer -->
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
</bean>
<!-- 擴展RedisCacheManager -->
<bean id="cacheManager" class="com.we.core.web.cache.TFRedisCacheManager">
<constructor-arg ref="redisTemplate" />
<!-- 是否使用前綴 默認: -->
<!--<property name="usePrefix" value="true" />-->
<!-- 默認有效期1h (60 * 60 = 3600秒) -->
<property name="defaultExpiration" value="${redis.expiration}" />
</bean>
<!-- ******************** redis緩存 **********************-->
</beans>
(3).config/spring-context.xml中添加
<import resource="spring-data-redis.xml" />
注解使用
概況
基於注解的緩存聲明,需要掌握的有:@Cacheable、@CachePut 、 @CacheEvict 和@Caching
以下列舉了幾種常用的使用屬性,詳情可自行查閱
@Cacheable(value="",condition="",key="",unless="")
public @interface Cacheable{
String[] value(); //緩存的名字,可以把數據寫到多個緩存,我們擴展了屬性:area#60*10, area是value,60*10是緩存時間(單位秒),不加走默認(1h)
String key() default ""; //緩存key,如果不指定將使用默認的KeyGenerator生成,后邊介紹
String condition() default ""; //滿足緩存條件的數據才會放入緩存,condition在調用方法之前和之后都會判斷
String unless() default ""; //用於否決緩存更新的,不像condition,該表達只在方法執行之后判斷,此時可以拿到返回值result進行判斷了
String keyGenerator() default ""; //指定key規則
}
@CachePut(value="",condition="",key="",unless="")
public @interface CachePut {
String[] value(); //緩存的名字,可以把數據寫到多個緩存
String key() default ""; //緩存key,如果不指定將使用默認的KeyGenerator生成,后邊介紹
String condition() default ""; //滿足緩存條件的數據才會放入緩存,condition在調用方法之前和之后都會判斷
String unless() default ""; //用於否決緩存更新的,不像condition,該表達只在方法執行之后判斷,此時可以拿到返回值result進行判斷了
}
@Cacheable(value="",condition="",key="",unless="")
public @interface CacheEvict {
String[] value(); //緩存的名字,可以把數據寫到多個緩存
String key() default ""; //緩存key,如果不指定將使用默認的KeyGenerator生成,后邊介紹
String condition() default ""; //滿足緩存條件的數據才會放入緩存,condition在調用方法之前和之后都會判斷
boolean allEntries() default false; //是否移除所有數據
boolean beforeInvocation() default false;//是調用方法之前移除/還是調用之后移除
@Caching(value="",condition="",key="",unless="")
public @interface Caching {
Cacheable[] cacheable() default {}; //從緩存獲取多個,如果沒有則執行方法體,獲取值后加入緩存
CachePut[] put() default {}; //緩存多個
CacheEvict[] evict() default {}; //從緩存移除多個
}
@Cacheable
較常用,用在查詢方法上,先從緩存中讀取,如果緩存不存在再調用該方法獲取數據,然后把返回的數據添加到緩存中去
正如其名字,@Cacheable用於添加在需高速緩存的方法上。這些方法默認會以參數為主鍵把返回結果存儲到高速緩存中,以便在隨后的調用(使用相同的參數)方法,直接返回高速緩存中的值,不需要實際執行此方法。
-
最簡單的方式,只需要聲明一個相關緩存策略的名稱
@Cacheable("area#60*10")
public Book getAreaVersion4(String code) {...}
-
也可以設置多個緩沖塊,其中一個緩沖塊命中即會返回,並會同步其他緩存塊:
@Cacheable(value = {"area#60*10","city#60*30"})
public Book getAreaVersion4(String code) {...}
-
定制key,且加同步
@Cacheable(value = {"area#60*10"}, key = "'code:'+#code",sync = true)
public AreaDto getAreaVersion4(String code) {
return areaBaseService.get (code);
}
-
定制key,且加同步,加條件
@Cacheable(value = {"area#60*10"}, key = "'code:'+#code",sync = true, condition = "#code=='100000'")
public AreaDto getAreaVersion4(String code) {
return areaBaseService.get (code);
}
@CacheEvict
主要對方法配置,用來標記要清空緩存的方法,當這個方法被調用並滿足一定條件后,即會清空緩存。
- 參數解析:
value:緩存的位置,不能為空。
key:緩存的key,默認為空。
condition:觸發的條件,只有滿足條件的情況才會清楚緩存,默認為空,支持SpEL。
allEntries:true表示清除value中的全部緩存,默認為false。
/**
* 情況area#60*10下所有緩存
*/
@CacheEvict(value = {"area#60*10"}, key = "'code:'+#code", condition = "#code=='100000'")
public AreaDto delete(String code) {
return areaBaseService.delete (code);
}
/**
* 只要執行了delArea2方法,就刷新緩存名為”getAreaVersion4”下面的所有緩存
*/
@Caching(evict = {@CacheEvict(value = {"getAreaVersion4#60*5"}, allEntries = true)})
public void delArea2() {
}
@CachePut
主要針對方法的配置,能夠根據方法的請求參數對其結果進行緩存,和@Cacheable不同的是,它每次都會觸發真實方法的調用。
@CachePut(value = {"area#60*10"}, key = "'code:'+#code",sync = true, condition = "#code=='100000'")
public AreaDto getAreaVersion4(String code) {
return areaBaseService.get (code);
}
其他自行查閱
spring-data-redis
自定義緩存注解
1.更新項目包
- we-core-web
2.添加默認配置
-
在apollo中添加 或者 在config/config.properties中添加
優先級順序:1、apollo;2、配置文件;
#緩存時間范圍
cache.cacheTime=300,400
#同步等待時間
cache.syncWaitTime=3
#空值緩存時間
cache.nullCacheTime=60
3.應用
-
使用demo
/**
* 目標方法
* <p&
* 支持限流
* 支持穿透
* 支持異步處理
* </p&
*
* @param code
* @return
*/
@TFCacheable(groupName = CACHE_GROUP_NAME, cacheTime = {300, 400}, syncWaitTime = 300)
public AreaDto getXXX(String code) {
return xxxBaseService.get (code);
}
注解介紹
/**
* 分組名
*/
String groupName() default "";
/**
* 緩存的時間范圍
* <br/&
* 過期時間,單位為秒
*
* <p&
* 格式:minTime-maxTime,如:60-120
* </p&
*/
int[] cacheTime() default 0;
/**
* 是否同步
* 同步排隊時間:{@link #syncWaitTime}.
* <p&
* 細粒度同步鎖,鎖定級別:參數級別
* </p&
* @see #syncWaitTime
*/
boolean sync() default true;
/**
* 同步等待時間
* <br/&
* 過期時間,單位為秒
*
* <p&
* 過期時間,單位為秒
* 如果開啟同步,默認排隊時間,超過后,拋超時異常
* </p&
* @see #sync
*/
int syncWaitTime() default 0;
/**
* 空值緩存時間
*
* <p&
* 空值會緩存短暫的時間,防止方法請求不斷請求數據庫,減少穿透幾率
* </p&
*/
int nullCacheTime() default 0
示例
@Cacheable(value = "ActivityScopeRedis#60*60",key = "#root.methodName + #activityId") public List<ActivityScopeDto> findByActivityId(long activityId) { return activityScopeBaseDao.findByActivityId(activityId); }