1.redis 的xml文件配置(aop切面的方式)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Redis连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWait}"/>
</bean>
<!-- 创建Redis连接工厂-->
<bean id="jeditConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"/>
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="timeout" value="${redis.timeout}"/>
</bean>
<!-- 如果操作对象,是复杂类型 用 jdkSerializationRedisSerializer 将对象转化成数组 -->
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer">
</bean>
<!--操作字符串用 stringReadisSerializer-->
<bean id="stringReadisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer">
</bean>
<!-- 创建一个RedisTemplate组件-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jeditConnectionFactory"/>
<!-- 指定key和value的序列化策-->
<property name="keySerializer" ref="stringReadisSerializer"/>
<property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>
</bean>
<bean id="redisUtil" class="com.hfxt.controller.redis.RedisUtil">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
<!-- 通过aop实现缓存拦截器的配置-->
<bean id="methodInterceptor" class="com.hfxt.controller.redis.MethodCacheInterceptor">
<property name="redisUtil" ref="redisUtil"/>
<property name="defaultCacheExpireTime" value="360000"/>
<property name="targetNamesList">
<list>
<value></value>
</list>
</property>
<property name="methodNamesList">
<list>
<value></value>
</list>
</property>
</bean>
<aop:config>
<!-- 定义切点-->
<aop:pointcut id="pointcut" expression="execution(* com.hfxt.service.*.*(..)) "/>
<!-- 植入拦截器设置-->
<aop:advisor advice-ref="methodInterceptor" pointcut-ref="pointcut"/>
</aop:config>
(普通方式)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Redis连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWait}"/>
</bean>
<!-- 创建Redis连接工厂-->
<bean id="jeditConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"/>
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="timeout" value="${redis.timeout}"/>
</bean>
<!-- 创建一个RedisTemplate组件-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jeditConnectionFactory"/>
</bean>
<bean id="redisUtil" class="com.hfxt.controller.redis.RedisUtil">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
</beans>
2.工具类
2.1redisUtil
package com.hfxt.controller.redis;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
/**
* Redis工具类
*/
public class RedisUtil {
private RedisTemplate<Serializable, Object> redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
2.2MethodCacheInterceptor
package com.hfxt.controller.redis;
import java.util.List;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MethodCacheInterceptor implements MethodInterceptor {
private RedisUtil redisUtil;
private List<String> targetNamesList; // 禁用缓存的类名列表
private List<String> methodNamesList; // 禁用缓存的方法列表
private String defaultCacheExpireTime; // 缓存默认的过期时间
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() {
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;
}
}
3.controller 层处理
package com.hfxt.controller;
import com.hfxt.controller.redis.RedisUtil;
import com.hfxt.entity.FilmInfo;
import org.springframework.context.annotation.Conditional;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/shop")
public class ShopController extends BaseController {
@Resource
protected RedisTemplate redisTemplate;
@RequestMapping("/shop.html")
public String shop()
{
Object count =redisTemplate.boundValueOps("name").get();
System.out.println(count);
if (count == null) {
redisTemplate.boundValueOps("name").set("zhangsan");
}else {
System.out.println("从redis中获取");
System.out.println(count);
}
return "shop";
}
@Resource
protected RedisUtil redisUtil;
@RequestMapping("/shop2.html")
public String shop2()
{
Object count =redisUtil.get("name");
System.out.println(count);
if (count == null) {
// redisTemplate.boundValueOps("name").set("zhangsan");
redisUtil.set("name","lisi");
}else {
System.out.println("从redis中获取");
System.out.println(count);
}
return "shop";
}
@RequestMapping("/shop3.html")
public String shop3 ()
{
List<FilmInfo> list= (List<FilmInfo>) redisUtil.get("infolist");
if (list == null) {
list=filmInfoService.getFilmInfosall();
redisUtil.set("infolist",list);
}else {
System.out.println("从redis中获取");
}
return "shop";
}
}
3.contoller 层进行缓存
package com.hfxt.controller;
import com.hfxt.controller.redis.RedisUtil;
import com.hfxt.entity.FilmInfo;
import org.springframework.context.annotation.Conditional;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/shop")
public class ShopController extends BaseController {
@Resource
protected RedisTemplate redisTemplate;
@RequestMapping("/shop.html")
public String shop()
{
Object count =redisTemplate.boundValueOps("name").get();
System.out.println(count);
if (count == null) {
redisTemplate.boundValueOps("name").set("zhangsan");
}else {
System.out.println("从redis中获取");
System.out.println(count);
}
return "shop";
}
@Resource
protected RedisUtil redisUtil;
@RequestMapping("/shop2.html")
public String shop2()
{
Object count =redisUtil.get("name");
System.out.println(count);
if (count == null) {
// redisTemplate.boundValueOps("name").set("zhangsan");
redisUtil.set("name","lisi");
}else {
System.out.println("从redis中获取");
System.out.println(count);
}
return "shop";
}
@RequestMapping("/shop3.html")
public String shop3 ()
{
List<FilmInfo> list= (List<FilmInfo>) redisUtil.get("infolist");
if (list == null) {
list=filmInfoService.getFilmInfosall();
redisUtil.set("infolist",list);
}else {
System.out.println("从redis中获取");
}
return "shop";
}
}