码迷,mamicode.com
首页 > 编程语言 > 详细

redis spring缓存配置

时间:2015-03-08 00:11:17      阅读:2759      评论:0      收藏:0      [点我收藏+]

标签:redis   缓存   spring   

使用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="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >
          <property name="maxIdle" value="${redis.maxIdle}" />
          <property name="maxActive" value="${redis.maxActive}" />
          <property name="maxWait" value="${redis.maxWait}" />
          <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean >

    <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 >
    <!-- cache配置 -->
    <bean id="methodCacheInterceptor" class="com.xxx.cache.MethodCacheInterceptor" >
          <property name="redisUtil" ref="redisUtil" />
    </bean >
    <bean id="redisUtil" class="com.xxx.framework.util.RedisUtil" >
          <property name="redisTemplate" ref="redisTemplate" />
    </bean >
    <bean id="methodCachePointCut"
         class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" >
          <property name="advice" >
              <ref local="methodCacheInterceptor" />
          </property>
          <property name="patterns" >
              <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("cacheConf.properties" );
             Properties p = new Properties();
             p.load(in);
              // 分割字符串
             String[] targetNames = p.getProperty("targetNames" ).split(",");
             String[] methodNames = p.getProperty("methodNames" ).split(",");
             
              //加载过期时间设置
              defaultCacheExpireTime = Long.valueOf(p.getProperty("defaultCacheExpireTime"));
              xxxRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxRecordManager"));
              xxxSetRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxSetRecordManager"));
              // 创建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[i]);
                 }
                  if(i < methodNames.length ) {
                      methodNamesList.add(methodNames[i]);
                 }
             }
         } 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("com.service.impl.xxxRecordManager" )){
                                redisUtil.set(tkey, tvalue,xxxRecordManagerTime );
                          } else if(tkey.startsWith("com.service.impl.xxxSetRecordManager" )){
                                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( "_").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;
    }
}

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

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方法,否则可能会出现序列化失败的错误。

redis spring缓存配置

标签:redis   缓存   spring   

原文地址:http://blog.csdn.net/liuchangqing123/article/details/44122825

(2)
(3)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!