spring增加缓存最简单的方法
添加配置信息
(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会降低性能,但是可以检测链接有效性,默认falseredis.testOnBorrow=true#返回前会先校验这个链接有效性,如果无效会被销毁,默认值falseredis.testOnReturn=trueredis.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/beanshttp://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/cachehttp://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); }

浙公网安备 33010602011771号