设为首页 收藏本站
查看: 1339|回复: 0

[经验分享] redis spring缓存配置

[复制链接]

尚未签到

发表于 2015-11-12 11:41:36 | 显示全部楼层 |阅读模式
使用redis做缓存的思路是在spring的项目中配置拦截器,在service层做切面,在findXXX或者getXXX等方法上进行拦截判断是否缓存即可。



1.环境:spring 3.1.2 + spring data redis 1.0.0+ jedis 2.1.0


  2.spring配置文件配置:
   <!-- jedis 配置 -->
<bean id=&quot;poolConfig&quot; class=&quot;redis.clients.jedis.JedisPoolConfig&quot; >
<property name=&quot;maxIdle&quot; value=&quot;${redis.maxIdle}&quot; />
<property name=&quot;maxActive&quot; value=&quot;${redis.maxActive}&quot; />
<property name=&quot;maxWait&quot; value=&quot;${redis.maxWait}&quot; />
<property name=&quot;testOnBorrow&quot; value=&quot;${redis.testOnBorrow}&quot; />
</bean >
<bean id=&quot;connectionFactory&quot;
class=&quot;org.springframework.data.redis.connection.jedis.JedisConnectionFactory&quot; >
<property name=&quot;poolConfig&quot; ref=&quot;poolConfig&quot; />
<property name=&quot;port&quot; value=&quot;${redis.port}&quot; />
<property name=&quot;hostName&quot; value=&quot;${redis.host}&quot; />
<property name=&quot;password&quot; value=&quot;${redis.password}&quot; />
<property name=&quot;timeout&quot; value=&quot;${redis.timeout}&quot; ></property>
</bean >
<bean id=&quot;redisTemplate&quot; class=&quot;org.springframework.data.redis.core.RedisTemplate&quot; >
<property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; />
<property name=&quot;keySerializer&quot; >
<bean
class=&quot;org.springframework.data.redis.serializer.StringRedisSerializer&quot; />
</property>
<property name=&quot;valueSerializer&quot; >
<bean
class=&quot;org.springframework.data.redis.serializer.JdkSerializationRedisSerializer&quot; />
</property>
</bean >
<!-- cache配置 -->
<bean id=&quot;methodCacheInterceptor&quot; class=&quot;com.xxx.cache.MethodCacheInterceptor&quot; >
<property name=&quot;redisUtil&quot; ref=&quot;redisUtil&quot; />
</bean >
<bean id=&quot;redisUtil&quot; class=&quot;com.xxx.framework.util.RedisUtil&quot; >
<property name=&quot;redisTemplate&quot; ref=&quot;redisTemplate&quot; />
</bean >
<bean id=&quot;methodCachePointCut&quot;
class=&quot;org.springframework.aop.support.RegexpMethodPointcutAdvisor&quot; >
<property name=&quot;advice&quot; >
<ref local=&quot;methodCacheInterceptor&quot; />
</property>
<property name=&quot;patterns&quot; >
<list>
<!-- 需要缓存的方法 正则表达式 -->
<value> com\.xxx\..*\.service\. impl\..*list.*</value >
<value> com\.xxx\..*\.service\. impl\..*find.*</value >
<value> com\.xxx\..*\.service\. impl\..*get.*</value >
</list>
</property>
</bean >

3.redis工具类


  import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
/**
* redis cache 工具类
*
*/
public final class RedisUtil {
private Logger logger = Logger.getLogger(RedisUtil.class);
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;
}
}


4.全局缓存拦截器


  import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import com.xxx.framework.util.RedisUtil;
import framework.utils.string.StringUtil;
public class MethodCacheInterceptor implements MethodInterceptor {
private Logger logger = Logger.getLogger(MethodCacheInterceptor. class);
private RedisUtil redisUtil;
private List<String> targetNamesList; // 不加入缓存的service名称
private List<String> methodNamesList; // 不加入缓存的方法名称
private Long defaultCacheExpireTime; //缓存默认的过期时间
private Long xxxRecordManagerTime; //
private Long xxxSetRecordManagerTime; //
/**
* 初始化读取不需要加入缓存的类名和方法名称
*/
public MethodCacheInterceptor() {
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(&quot;cacheConf.properties&quot; );
Properties p = new Properties();
p.load(in);
// 分割字符串
String[] targetNames = p.getProperty(&quot;targetNames&quot; ).split(&quot;,&quot;);
String[] methodNames = p.getProperty(&quot;methodNames&quot; ).split(&quot;,&quot;);
//加载过期时间设置
defaultCacheExpireTime = Long.valueOf(p.getProperty(&quot;defaultCacheExpireTime&quot;));
xxxRecordManagerTime = Long.valueOf(p.getProperty(&quot;com.service.impl.xxxRecordManager&quot;));
xxxSetRecordManagerTime = Long.valueOf(p.getProperty(&quot;com.service.impl.xxxSetRecordManager&quot;));
// 创建list
targetNamesList = new ArrayList<String>(targetNames.length );
methodNamesList = new ArrayList<String>(methodNames.length );
Integer maxLen = targetNames. length > methodNames.length ? targetNames.length : methodNames.length;
// 将不需要缓存的类名和方法名添加到list中
for(int i = 0; i < maxLen; i++) {
if(i < targetNames.length ) {
targetNamesList.add(targetNames);
}
if(i < methodNames.length ) {
methodNamesList.add(methodNames);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object value = null;
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
// 不需要缓存的内容
if (!isAddCache(StringUtil.subStrForLastDot(targetName), methodName)) {
// 执行方法返回结果
return invocation.proceed();
}
Object[] arguments = invocation.getArguments();
String key = getCacheKey(targetName, methodName, arguments);
System. out.println(key);
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() {
if(tkey.startsWith(&quot;com.service.impl.xxxRecordManager&quot; )){
redisUtil.set(tkey, tvalue,xxxRecordManagerTime );
} else if(tkey.startsWith(&quot;com.service.impl.xxxSetRecordManager&quot; )){
redisUtil.set(tkey, tvalue,xxxSetRecordManagerTime );
} else{
redisUtil.set(tkey, tvalue,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)) {
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( &quot;_&quot;).append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sbu.append( &quot;_&quot;).append(arguments);
}
}
return sbu.toString();
}
public void setRedisUtil(RedisUtil redisUtil) {
this.redisUtil = redisUtil;
}
}

上面代码中掺杂了部分业务逻辑不是太好,可以继续优化一下哈。
  5.redis.properties文件


  redis.host=127.0.0.1
redis.port=6379
redis.password=
redis.maxIdle=100
redis.maxActive=300
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000


6.cacheConf.properties文件


  # 不需要加缓存的类和方法
# not add cache service name
targetNames=xxxRecordManager,xxxSetRecordManager,xxxStatisticsIdentificationManager
# not add cache method name
methodNames=
#设置过期时间
com.service.impl.xxxRecordManager= 60
com.service.impl.xxxSetRecordManager= 60
defaultCacheExpireTime=3600

7.注意拼接key时需要将相应的类生成toString方法,否则可能会出现序列化失败的错误。



版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-138287-1-1.html 上篇帖子: redis数据类型与基本操作 下篇帖子: 用脚本批量执行redis命令
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表