集成redis緩存后可以將數(shù)據(jù)庫的查詢接口,序列化到redis中,key就是注解中的參數(shù),例如@Cacheable("findUsers"): 存在redis中的key就是findUsers。緩存了這個結果之后再次請求這個方法就不會去數(shù)據(jù)庫中查,而是從redis緩存中讀取數(shù)據(jù),這樣就減少了跟數(shù)據(jù)庫之間的交互。然后修改、刪除、增加操作就會清除緩存,保持數(shù)據(jù)的一致性,同時有極大的提高了程序運行的效率
1.引入依賴包文件
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.4.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.創(chuàng)建redis.properties文件
#============================#
#==== Redis settings ====#
#============================#
#redis 服務器 IP
redis.host=127.0.0.1
#redis 服務器端口
redis.port=6380
#redis 密碼
redis.pass=123456
#redis 支持16個數(shù)據(jù)庫(相當于不同用戶)可以使不同的應用程序數(shù)據(jù)彼此分開同時又存儲在相同的實例上
redis.dbIndex=0
#redis 緩存數(shù)據(jù)過期時間單位秒
redis.expiration=3000
#控制一個 pool 最多有多少個狀態(tài)為 idle 的jedis實例
redis.maxIdle=300
#控制一個 pool 可分配多少個jedis實例
redis.maxActive=600
#當borrow一個jedis實例時,最大的等待時間,如果超過等待時間,則直接拋出JedisConnectionException;
redis.maxWait=1000
#在borrow一個jedis實例時,是否提前進行alidate操作;如果為true,則得到的jedis實例均是可用的;
redis.testOnBorrow=true
3.創(chuàng)建redis-context文件
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:bean="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!--<context:property-placeholder location="classpath:application.properties"/>-->
<context:property-placeholder location="classpath:redis.properties"/>
<!-- redis config start -->
<!-- 配置JedisPoolConfig實例 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 配置JedisConnectionFactory -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="database" value="${redis.dbIndex}" />
<property name="password" value="${redis.pass}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- 配置RedisCacheManager -->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg name="redisOperations" ref="redisTemplate" />
<property name="defaultExpiration" value="${redis.expiration}" />
</bean>
<!-- 配置RedisCacheConfig -->
<bean id="redisCacheConfig" class="com.lepu.redis.RedisCacheConfig">
<constructor-arg ref="jedisConnectionFactory" />
<constructor-arg ref="redisTemplate" />
<constructor-arg ref="redisCacheManager" />
</bean>
<!-- redis config end -->
</beans>
4.redis緩存配置類,會在redis-context配置文件中注冊這個bean。
/**
* @Author: chuan.bai
* @Description
* 該配置類繼承自 org.springframework.cache.annotation.CachingConfigurerSupport
* 并實現(xiàn) org.springframework.cache.annotation.CachingConfigurer 的方法。
* 通俗一點,該類告訴 spring 當前使用的緩存服務為 redis 并自定義了緩存 key 生成的規(guī)則
* @Date: Created on 14:45 27/01/2018
* @Modified By:
*/
/**
* 通過spring管理redis緩存配置
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
protected final static Logger log = LoggerFactory.getLogger(RedisCacheConfig.class);
private volatile JedisConnectionFactory mJedisConnectionFactory;
private volatile RedisTemplate<String, String> mRedisTemplate;
private volatile RedisCacheManager mRedisCacheManager;
public RedisCacheConfig() {
super();
}
public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate<String, String> mRedisTemplate, RedisCacheManager mRedisCacheManager) {
super();
this.mJedisConnectionFactory = mJedisConnectionFactory;
this.mRedisTemplate = mRedisTemplate;
this.mRedisCacheManager = mRedisCacheManager;
}
public JedisConnectionFactory redisConnectionFactory() {
return mJedisConnectionFactory;
}
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
return mRedisTemplate;
}
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
return mRedisCacheManager;
}
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
在需要緩存的方法上面添加相應注釋
@Cacheable spring 會在其被調用后將返回值緩存起來,以保證下次利用同樣的參數(shù)來執(zhí)行該方法時可以直接從緩存中獲取結果,而不需要再次執(zhí)行該方法。
@CachePut 標注的方法在執(zhí)行前不會去檢查緩存中是否存在之前執(zhí)行過的結果,而是每次都會執(zhí)行該方法,并將執(zhí)行結果以鍵值對的形式存入指定的緩存中。
@CacheEvict 用來標注在需要清除緩存元素的方法或類上的。
例如:
@Cacheable(value = "getAllUser") :標注該方法查詢的結果進入緩存,再次訪問時直接讀取緩存中的數(shù)據(jù)
@CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true)//清空緩存,allEntries變量表示所有對象的緩存都清除
一般在對數(shù)據(jù)做修改嗎,刪除的方法中,會插入該注解,防止redis數(shù)據(jù)和mysql不同步