SSM之整合Redis
阿新 • • 發佈:2019-02-14
Redis安裝與使用
第一步當然是安裝Redis,這裡以Windows上的安裝為例。
- 首先下載Redis,可以選擇msi或zip包安裝方式
- zip方式需開啟cmd視窗,在解壓後的目錄下執行redis-server redis.windows.conf
啟動Redis
- 採用msi方式安裝後Redis預設啟動,不需要進行任何配置
- 可以在redis.windows.conf檔案中修改Redis埠號、密碼等配置,修改完成後使用redis-server redis.windows.conf
命令重新啟動
- 在Redis安裝目錄下執行redis-cli -h 127.0.0.1 -p 6379 -a 密碼
- 如果報錯
(error) ERR operation not permitted
,使用auth 密碼
進行驗證
SSM整合Redis
這裡直接在上一篇SSM之框架整合的基礎上進行Redis整合
配置pom.xml引入Redis依賴
<!--redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version >1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=redis
redis.maxIdle =100
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
defaultCacheExpireTime=3600
applicationContext-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--引入Redis配置檔案-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<!-- jedis 連線池配置 -->
<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}"/>
</bean>
<!-- redis連線工廠 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"/>
<property name="port" value="${redis.port}"/>
<property name="hostName" value="${redis.host}"/>
<property name="password" value="${redis.password}"/>
<property name="timeout" value="${redis.timeout}"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
<!-- 快取攔截器配置 -->
<bean id="methodCacheInterceptor" class="com.zkh.interceptor.MethodCacheInterceptor">
<property name="redisUtil" ref="redisUtil"/>
<property name="defaultCacheExpireTime" value="${defaultCacheExpireTime}"/>
<!-- 禁用快取的類名列表 -->
<property name="targetNamesList">
<list>
<value></value>
</list>
</property>
<!-- 禁用快取的方法名列表 -->
<property name="methodNamesList">
<list>
<value></value>
</list>
</property>
</bean>
<bean id="redisUtil" class="com.zkh.util.RedisUtil">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
<!--配置切面攔截方法 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="controllerMethodPointcut" expression="
execution(* com.zkh.service.impl.*.select*(..))"/>
<aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/>
</aop:config>
</beans>
MethodCacheInterceptor.java
package com.zkh.interceptor;
import com.zkh.util.RedisUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import java.util.List;
/**
* Redis快取過濾器
*/
public class MethodCacheInterceptor implements MethodInterceptor {
private RedisUtil redisUtil;
private List<String> targetNamesList; // 禁用快取的類名列表
private List<String> methodNamesList; // 禁用快取的方法列表
private String defaultCacheExpireTime; // 快取預設的過期時間
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object value = null;
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
if (!isAddCache(targetName, methodName)) {
// 跳過快取返回結果
return invocation.proceed();
}
Object[] arguments = invocation.getArguments();
String key = getCacheKey(targetName, methodName, arguments);
try {
// 判斷是否有快取
if (redisUtil.exists(key)) {
return redisUtil.get(key);
}
// 寫入快取
value = invocation.proceed();
if (value != null) {
final String tkey = key;
final Object tvalue = value;
new Thread(new Runnable() {
@Override
public void run() {
redisUtil.set(tkey, tvalue, Long.parseLong(defaultCacheExpireTime));
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
if (value == null) {
return invocation.proceed();
}
}
return value;
}
/**
* 是否加入快取
*
* @return
*/
private boolean isAddCache(String targetName, String methodName) {
boolean flag = true;
if (targetNamesList.contains(targetName)
|| methodNamesList.contains(methodName) || targetName.contains("$$EnhancerBySpringCGLIB$$")) {
flag = false;
}
return flag;
}
/**
* 建立快取key
*
* @param targetName
* @param methodName
* @param arguments
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) {
StringBuffer sbu = new StringBuffer();
sbu.append(targetName).append("_").append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sbu.append("_").append(arguments[i]);
}
}
return sbu.toString();
}
public void setRedisUtil(RedisUtil redisUtil) {
this.redisUtil = redisUtil;
}
public void setTargetNamesList(List<String> targetNamesList) {
this.targetNamesList = targetNamesList;
}
public void setMethodNamesList(List<String> methodNamesList) {
this.methodNamesList = methodNamesList;
}
public void setDefaultCacheExpireTime(String defaultCacheExpireTime) {
this.defaultCacheExpireTime = defaultCacheExpireTime;
}
}
效果展示
剛開始Redis中沒有任何記錄,接下來訪問一下第一頁記錄
再檢視快取,記錄已經存如Redis,並且第一次訪問會從Mysql中讀取資料
按F5
重新整理頁面,從Tomcat控制檯可以看到沒有進行SQL查詢,而是直接從Redis中讀取快取資料,減輕了資料庫的負擔
具體程式碼已釋出在Github上,地址:SSM