1.pom文件

            <!--redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>

2.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!--引入Redis配置文件 需要的时候进行配置-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/redis.properties</value>
</list>
</property>
</bean> <!--引入Redis配置文件 方式二-->
<!-- <context:property-placeholder location="classpath:properties/redis.properties" ignore-unresolvable="true"/> --> <!-- jedis 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="10" />
<property name="maxIdle" value="10"/><!-- "${redis.maxIdle}" -->
<property name="maxWait" value="1000"/><!--${redis.maxWait} -->
<property name="testOnBorrow" value="true"/><!-- ${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}"/><!--${redis.port} -->
<property name="hostName" value="${redis.ip}"/>
<!-- <property name="password" value="${redis.pass}"/> -->
<property name="timeout" value="100000"></property><!-- ${redis.timeout} -->
</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>
<!-- cache配置 -->
<bean id="methodCacheInterceptor" class="cn.com.scooper.interceptor.MethodCacheInterceptor">
<property name="redisUtil" ref="redisUtil"/>
<property name="defaultCacheExpireTime" value="${redis.cacheExpireTime}"/><!-- ${redis.cacheExpireTime} -->
<property name="targetNamesList">
<list>
<value></value>
</list>
</property>
<property name="methodNamesList">
<list>
<value>getAccountStatus</value>
</list>
</property>
</bean>
<bean id="redisUtil" class="cn.com.scooper.utils.RedisUtil">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
<!--配置切面拦截方法 -->
<aop:config >
<aop:pointcut id="controllerMethodPointcut" expression="execution(* cn.com.scooper.impl..*.*(..))"/>
<aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/>
</aop:config> </beans>

3.Redis配置文件 redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.maxIdle=100
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
defaultCacheExpireTime=3600
redis.cacheExpireTime=3600

4.创建拦截器

package cn.com.scooper.interceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; import cn.com.scooper.common.annotation.ClearInterceptor;
import cn.com.scooper.common.annotation.NotToCache;
import cn.com.scooper.common.constant.CommonConstant;
import cn.com.scooper.utils.RedisUtil; import java.util.List; /**
* Redis缓存过滤器
* 主要经过以下步骤:
1.查看当前方法是否在我们自定义的方法中,如果不是的话就直接返回,不进入拦截器。
2.之后利用反射获取的类名、方法名、参数生成redis的key。
3.用key在redis中查询是否已经有缓存。
4.有缓存就直接返回缓存内容,不再继续查询数据库。
5.如果没有缓存就查询数据库并将返回信息加入到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 = creatCacheKey(targetName, methodName, arguments);
try {
// 判断是否有缓存
if (redisUtil.exists(key)) {
return redisUtil.get(key);
}
// 写入缓存
value = invocation.proceed();
if (invocation.getMethod().getAnnotation(NotToCache.class) == null && value != null ) {
final String tkey = key;
final Object tvalue = value;
new Thread(new Runnable() {
@Override
public void run() {
if(Long.parseLong(defaultCacheExpireTime) > 0){
redisUtil.set(tkey, tvalue, Long.parseLong(defaultCacheExpireTime));
}else{
redisUtil.set(tkey, tvalue);
}
}
}).start();
}else if(invocation.getMethod().getAnnotation(NotToCache.class) != null ){
redisUtil.removePattern(CommonConstant.KEY_PREFIX+CommonConstant.KEY_SPLIT_CHAR+targetName+"*");
}
} 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 creatCacheKey(String targetName, String methodName,Object[] arguments) { StringBuffer sbu = new StringBuffer(CommonConstant.KEY_PREFIX);
sbu.append(CommonConstant.KEY_SPLIT_CHAR).append(targetName).append(CommonConstant.KEY_SPLIT_CHAR).append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sbu.append(CommonConstant.KEY_SPLIT_CHAR).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;
}
}

5.Redis工具类

package cn.com.scooper.utils;
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){
for (Serializable key : keys) {
redisTemplate.delete(key);
}
}
} /**
* 删除对应的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;
}
}

Redis入门到高可用(十)—— Spring与Redis的整合的更多相关文章

  1. Redis入门到高可用(二)—— Redis启动及使用

    1. 三种启动方式 ♦️  最简启动 ./redis-server 使用Redis默认配置进行启动; ♦️  动态参数启动 * redis-server --port 6380  更改端口为6380并 ...

  2. Redis入门到高可用(四)—— Redis的五种数据结构的内部编码

    Redis的五种数据结构的内部编码

  3. Redis入门到高可用(十八)—— 主从复制

    一.单机有什么问题 1.机器故障 2.容量瓶颈 3.QPS瓶颈 二.主从复制 1.数据副本(高可用.分布式基础) 2.拓展读性能(读写分离)  简单总结: 三.主从复制配置 四.主从复制配置-实验演示 ...

  4. Redis入门到高可用(十九)——Redis Sentinel

    一.Redis  Sentinel架构     二.redis sentinel安装与配置 四.客户端连接Sentinel            四.实现原理—— 故障转移演练(客户端高可用) 五.实 ...

  5. Redis入门到高可用(一)——初识Redis

    一.Redis是什么 * 开源 * 基于键值的存储服务系统 * 支持多种数据结构 * 高性能,功能丰富 二.Redis特性 ♦️ 概述 * 速度快 * 支持持久化 * 支持多种数据结构 * 支持多种编 ...

  6. Redis入门到高可用(二十)——Redis Cluster

    一.呼唤集群 二.数据分布概论      三.哈希分布 1.节点取余 2.一致性哈希 添加一个node5节点时,只影响n1和n2之间的数据   3.虚拟槽分区 四.基本架构 五.redis clust ...

  7. Redis入门到高可用(十六)—— 持久化

    一.持久化概念 二.持久化方式 三.redis持久化方式之——RDB 1.什么是RDB 在 Redis 运行时, RDB 程序将当前内存中的数据库快照保存到磁盘文件中, 在 Redis 重启动时, R ...

  8. Redis入门到高可用(十二)—— pipeline

    一.回忆通信模型 二.流水线 1.什么是流水线 2.pipeline-Jedis实现 3.与原生M(mget,mset等)操作对比 M操作是原子操作 pipeline命令是非原子的,Redis服务器会 ...

  9. Redis入门到高可用(十五)—— GEO

    一.简介 二.应用场景 三.API 1.geoadd 2.geopos 3.geodist 4.georadius 四.相关说明

随机推荐

  1. 《objective-c基础教程》学习笔记(六)—— 复合方法

    今天我们要讲的复合,当然不是小情侣吵着分手,然后又在一起的复合. 复合遵循一个合成复用原则,又称为组合或者聚合复用原则.该原则的内容是:尽量使用对象组合,而不是继承来达到复用的目的.用聚合可以使系统更 ...

  2. SpringMVC中 -- @RequestMapping的作用及用法

    一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.x ...

  3. ValueError: {0} is not a valid coordinate or range问题解决

    获取excel多列方法: >>> colC = ws['C'] >>> col_range = ws['C:D'] 采用python 实现时,开始列与结束列采用变量 ...

  4. css布局 - 垂直居中布局的一百种实现方式(更新中...)

    首先将垂直居中的现象和实现方式两大方向细分类如下: 接下来逐条累加不同情况下的垂直居中实现. 目录: 一.父元素高度固定时,单行文本 | 图片的垂直居中 1. line-height行高简单粗暴实现法 ...

  5. iOS - 开发中加载本地word/pdf文档说明

    最近项目中要加载一个本地的word/pdf等文件比如<用户隐私政策><用户注册说明>,有两种方法加载 > 用QLPreviewController控制器实现 步骤 : & ...

  6. PHP计算两个经纬度地点之间的距离

    /**  * 求两个已知经纬度之间的距离,单位为米  *   * @param lng1 $ ,lng2 经度  * @param lat1 $ ,lat2 纬度  * @return float 距 ...

  7. easyui---tree异步加载

    1.ul li的多级列表的html代码tree 2.利用jquery <ul id="tt"></ul> $('#tt').tree({ url:'tree ...

  8. hdu3613 Best Reward【Manacher】

    Best Reward Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total ...

  9. 蓝桥杯_算法训练_区间k大数查询

    问题描述 给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个. 输入格式 第一行包含一个数n,表示序列长度. 第二行包含n个正整数,表示给定的序列. 第三个包含一个正整数m,表示询问个数 ...

  10. Codeforces 1096D - Easy Problem - [DP]

    题目链接:http://codeforces.com/problemset/problem/1096/D 题意: 给出一个小写字母组成的字符串,如果该字符串的某个子序列为 $hard$,就代表这个字符 ...