ssm項目整合redis

添加jar

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

redis.properties

  ##########################
 ## redis缓存配置
  ##########################
  # redis主机IP
  redis.host=ip
  # redis端口
  redis.port=6379
  # 链接超时
  # redis.timeout=2000
 # 密码
  redis.password=***
 # 指定redis数据库
 # redis.database=2
 
 ##########################
 ## redis连接池配置
 ##########################
 # 最大连接数
 redis.maxTotal=30
 # 最大空闲连接数
 redis.maxIdle=10
 # 获取链接最大等待毫秒
 redis.maxWaitMillis=1000
 # 获取链接时检查有效性
 redis.testOnBorrow=true
 
 # 在空闲时监测有效性
 # redis.testWhileIdle=true
 # 链接耗尽时是否阻塞
 # redis.blockWhenExhausted=true
 # 每次释放链接的最大数目
 # redis.numTestsPerEvictionRun=1024
 # 释放链接的扫描间隔(毫秒)
 # redis.timeBetweenEvictionRunsMillis=30000
 # 最小空闲时间
 # redis.minEvictableIdleTimeMillis=1800000
 # 链接空闲多久后释放
 # redis.softMinEvictableIdleTimeMillis=10000

applicationContext-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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--引入Redis配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

    <!-- 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>
    <!-- 缓存拦截器配置 -->
    <bean id="methodCacheInterceptor" class="com.zkh.interceptor.MethodCacheInterceptor">
        <property name="redisUtil" ref="redisUtil"/>
        <property name="defaultCacheExpireTime" value="${defaultCacheExpireTime}"/>
        <!-- 禁用缓存的类名列表 -->
        <property name="targetNamesList">
            <list>
                <value></value>
            </list>
        </property>
        <!-- 禁用缓存的方法名列表 -->
        <property name="methodNamesList">
            <list>
                <value></value>
            </list>
        </property>
    </bean>
    <bean id="redisUtil" class="com.zkh.util.RedisUtil">
        <property name="redisTemplate" ref="redisTemplate"/>
    </bean>
    <!--配置切面拦截方法 -->
    <!-- <aop:config proxy-target-class="true">
        <aop:pointcut id="controllerMethodPointcut" expression="execution(* com.zkh.service.impl.*.select*(..))"/>
        <aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/>
    </aop:config> -->
</beans>

RedisUtil

package com.foxconn.system.util;

import java.io.Serializable;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class RedisUtil {
	 private static 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 static 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;
	    }
}

MethodCacheInterceptor.java

package com.zkh.interceptor;

import com.zkh.util.RedisUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.util.List;

/**
 * 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 = 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() {
                    @Override
                    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;
    }
}

test

RedisUtil.set(“ddd”,“rdis”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值