spring 和 redis整合,并且使用redis做session缓存服务器

所需jar

  1. commons-pool2-2.0.jar
  2. jedis-2.9.0.jar
  3. spring-data-redis-1.6.2.RELEASE.jar
  4. spring-session-1.2.1.RELEASE.jar

一 . xml配置文件

   
   <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
    <property name="maxIdle" value="${redis.maxIdle}" />  
       <property name="maxTotal" value="${redis.maxTotal}" />  
       <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>  
       <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
       <property name="testOnReturn" value="${redis.testOnReturn}"/>  
   bean>  

    
   <bean id="jedisConnectionFactory"  
       class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
       destroy-method="destroy">  
       <property name="hostName" value="${redis.host}" />  
       <property name="port" value="${redis.port}" />  
       <property name="poolConfig" ref="jedisPoolConfig" />  
   bean>  

    
    <bean  id="redisJdkSerializer" class="com.***.RedisJdkSerializer" />  
   
    <bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
        <property name="cookieName" value="JSESSIONID"/>
        
        
    bean>

    
    <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
        <property name="defaultRedisSerializer" ref="redisJdkSerializer" />
        
        <property name="maxInactiveIntervalInSeconds" value="1800"/> 
        <property name="cookieSerializer" ref="defaultCookieSerializer"/>
    bean>

二. redis配置项

redis.host=127.0.0.1
redis.port=6379
redis.maxIdle=300
redis.maxTotal=600
redis.maxWaitMillis=1000
redis.testOnBorrow=true
redis.testOnReturn=false

三. web.xml配置session代理,让spring接管session

注意: 放在第一个filter


<filter>
  <filter-name>springSessionRepositoryFilterfilter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
  <filter-name>springSessionRepositoryFilterfilter-name>
  <url-pattern>/*url-pattern>
filter-mapping>

四. 重写jdk序列化(如果没反序列化出错的问题不需要此项)

public class RedisJdkSerializer implements RedisSerializer<Object> {
    private Converterbyte[]> serializer = new SerializingConverter();

    public Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
            return objectInputStream.readObject();
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }

    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            throw new SerializationException("Cannot serialize", ex);
        }
    }
}

五. 附上RedisOpsUtil操作类

public class RedisOpsUtil {

    private static RedisTemplate redisTemplate;
    private static MdbRedisOpsUtil mdbRedisOpsUtil;
     /**
     * 前缀
     */
    public static final String KEY_PREFIX_VALUE = "default:value:";
    public static final String KEY_PREFIX_SET = "default:set:";
    public static final String KEY_PREFIX_LIST = "default:list:";

    public static MdbRedisOpsUtil newInstance(){
        if(null == mdbRedisOpsUtil){
            mdbRedisOpsUtil=new MdbRedisOpsUtil();
        }
        return mdbRedisOpsUtil;
    }
    private MdbRedisOpsUtil(){
        redisTemplate=getRedisTemplate();
    }

    /**
     * 获取spring redis模板操作
     */
    public RedisTemplate getRedisTemplate(){
        if(null == redisTemplate){
            redisTemplate=(RedisTemplate)ApplicationContextManager.get("redisTemplate");
        }
        return redisTemplate;
    }
    /**
     * 获取redis针对值数据缓存操作
     * @author luxian.zhang
     * @return
     */
    public  ValueOperations opsForValue(Class c){
        return redisTemplate.opsForValue();
    }
    /**
     * 获取redis针对列表数据缓存操作,元素有序,不唯一
     * @author luxian.zhang
     * @return
     */
    public  ListOperations opsForList(Class c){
        return redisTemplate.opsForList();
    }
    /**
     * 获取redis针对集合数据缓存操作,元素无序,唯一
     * @author luxian.zhang
     * @return
     */
    public  SetOperations opsForSet(Class c){
        return redisTemplate.opsForSet();
    }

    /**
     * 获取redis这对集合数据缓存操作,元素有序,唯一
     * @author luxian.zhang
     * @return
     */
    public  ZSetOperations opsForZSet(Class c){
        return redisTemplate.opsForZSet();
    }

    /**
     * 获取redis针对对象数据缓存操作
     */
    public  HashOperations opsForHash(Class c){
        return redisTemplate.opsForHash();
    }

    /**
     * 缓存value操作
     * @param k
     * @param v
     * @param time
     */
    public  boolean cacheValue(String k, T v, long time) {
        String key = KEY_PREFIX_VALUE + k;
        ValueOperations valueOps =  redisTemplate.opsForValue();
        valueOps.set(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 缓存value操作
     * @param k
     * @param v
     */
    public  boolean cacheValue(String k, T v) {
        return cacheValue(k, v, -1);
    }

    /**
     * 判断缓存是否存在
     * @param k
     */
    public boolean containsValueKey(String k) {
        return containsKey(KEY_PREFIX_VALUE + k);
    }

    /**
     * 判断缓存是否存在
     * @param k
     */
    public boolean containsSetKey(String k) {
        return containsKey(KEY_PREFIX_SET + k);
    }

    /**
     * 判断缓存是否存在
     * @param k
     */
    public boolean containsListKey(String k) {
        return containsKey(KEY_PREFIX_LIST + k);
    }

    public boolean containsKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取缓存
     * @param k
     */
    public  T getValue(Class c, String k) {
        ValueOperations valueOps =  redisTemplate.opsForValue();
        return valueOps.get(KEY_PREFIX_VALUE + k);
    }

    /**
     * 移除缓存
     * @param k
     */
    public boolean removeValue(String k) {
        return remove(KEY_PREFIX_VALUE + k);
    }

    public boolean removeSet(String k) {
        return remove(KEY_PREFIX_SET + k);
    }

    public boolean removeList(String k) {
        return remove(KEY_PREFIX_LIST + k);
    }

    /**
     * 移除缓存
     * @param key
     */
    public boolean remove(String key) {
        redisTemplate.delete(key);
        return true;
    }
    /**
     * 缓存set操作
     * @param k
     * @param v
     * @param time
     */
    public  boolean cacheSet(String k, T v, long time) {
        String key = KEY_PREFIX_SET + k;
        SetOperations valueOps =  redisTemplate.opsForSet();
        valueOps.add(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 缓存set
     * @param k
     * @param v
     */
    public  boolean cacheSet(String k, T v) {
        return cacheSet(k, v, -1);
    }

    /**
     * 缓存set
     * @param k
     * @param v 把set转换为数组
     * @param time
     */
    public  boolean cacheSet(String k, T[] v, long time) {
        String key = KEY_PREFIX_SET + k;
        SetOperations setOps =  redisTemplate.opsForSet();
        setOps.add(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 缓存set
     * @param k
     * @param v 把set转换为数组
     */
    public  boolean cacheSet(String k, T[] v) {
        return cacheSet(k, v, -1);
    }

    /**
     * 获取缓存set数据
     * @param c
     * @param k
     */
    public  Set getSet(Class c, String k) {
        SetOperations setOps = redisTemplate.opsForSet();
        return setOps.members(KEY_PREFIX_SET + k);
    }

    /**
     * list缓存
     * @param k
     * @param v
     * @param time
     */
    public  boolean cacheList(String k, T v, long time) {
        String key = KEY_PREFIX_LIST + k;
        ListOperations listOps =  redisTemplate.opsForList();
        listOps.rightPush(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 缓存list
     * @param k
     * @param v
     */
    public  boolean cacheList(String k, T v) {
        return cacheList(k, v, -1);
    }

    /**
     * 缓存list
     * @param k
     * @param v
     * @param time
     */
    public  boolean cacheList(String k, List v, long time) {
        String key = KEY_PREFIX_LIST + k;
        ListOperations listOps =  redisTemplate.opsForList();
        long l = listOps.rightPushAll(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 缓存list
     * @param k
     * @param v
     */
    public  boolean cacheList(String k, List v) {
       return cacheList(k, v, -1);
    }

    /**
     * 获取list缓存
     * @param c
     * @param k
     * @param start
     * @param end
     */
    public  List getList(Class c, String k, long start, long end) {
        ListOperations listOps =  redisTemplate.opsForList();
        return listOps.range(KEY_PREFIX_LIST + k, start, end);
    }

    /**
     * 获取总条数, 可用于分页
     * @param k
     */
    public long getListSize(String k) {
        ListOperations listOps =  redisTemplate.opsForList();
        return listOps.size(KEY_PREFIX_LIST + k);
    }

    /**
     * 移除list缓存
     * @param k
     */
    public boolean removeOneOfList(String k) {
        String key = KEY_PREFIX_LIST + k;
        ListOperations listOps =  redisTemplate.opsForList();
        listOps.rightPop(KEY_PREFIX_LIST + k);
        return true;
    }
}

你可能感兴趣的:(开源项目)