redis与spring结合使用

 推荐一篇文章:

http://mp.weixin.qq.com/s?__biz=MjM5NzMyMjAwMA==&mid=2651477079&idx=1&sn=dd366c247d6225ee77177f5909a6a9b1&scene=4#wechat_redirect


redis与spring结合使用,在 MethodInterceptor 里 将请求参数为key,返回结果为value,通过约定的命名规则,将访问频繁的且对权限控制要求不高的请求“自动”接入redis。


比在具体方法里 进行 存取操作 ,工作量跟维护成本低很多。


public class MethodCacheInterceptor implements MethodInterceptor {
 
    private RedisTemplate<Serializable, Object> redisTemplate;
    private Long defaultCacheExpireTime = 10l; // 缓存默认的过期时间,这里设置了10秒
 
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object value = null;
 
        String targetName = invocation.getThis().getClass().getName();
        String methodName = invocation.getMethod().getName();
 
        Object[] arguments = invocation.getArguments();
        String key = getCacheKey(targetName, methodName, arguments);
 
        try {
            // 判断是否有缓存
            if (exists(key)) {
                return getCache(key);
            }
            // 写入缓存
            value = invocation.proceed();
            if (value != null) {
                final String tkey = key;
                final Object tvalue = value;
                new Thread(new Runnable() {
                    public void run() {
                        setCache(tkey, tvalue, defaultCacheExpireTime);
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (value == null) {
                return invocation.proceed();
            }
        }
        return value;
    }
 
    /**
     * 创建缓存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();
    }
 
    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
 
    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object getCache(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 setCache(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;
    }
}



<!-- 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 >
 
    <!-- cache配置 -->
    <bean id="methodCacheInterceptor" class="com.test.redis.interceptor.MethodCacheInterceptor" >
          <property name="redisTemplate" ref="redisTemplate" />
    </bean >
 
    <!-- aop配置切点跟通知 -->
    <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="advice" ref="methodCacheInterceptor"/>
        <property name="pattern" value=".*ServiceImpl.*getTimestamp"/>
    </bean>
    
    <bean id="redisTestService" class="com.test.redis.RedisTestServiceImpl">
    </bean>



http://pan.baidu.com/s/1gf4QD0n


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值