1. 程式人生 > >spring 和 redis整合,並且使用redis做session快取伺服器

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配置檔案

   <!-- jedis連線池配置 -->
   <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> <!-- jedis連線工廠配置 --> <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> <!-- 重寫jdk序列化,解決反序列化找不到類的問題 --> <bean id="redisJdkSerializer" class="com.***.RedisJdkSerializer" /> <!-- 設定Cookie domain 和 名稱 --> <bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer"> <property name="cookieName" value="JSESSIONID"/> <!--設定Cookie的路徑,用於不同應用之間的session共享--> <!--<property name="cookiePath" value="/"/>--> </bean> <!-- spring redis session配置--> <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="defaultRedisSerializer" ref="redisJdkSerializer" /> <!-- sesson 過期時間--> <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

<!-- spring session 處理 -->
<filter>
  <filter-name>springSessionRepositoryFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSessionRepositoryFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

四. 重寫jdk序列化(如果沒反序列化出錯的問題不需要此項)

public class RedisJdkSerializer implements RedisSerializer<Object> {
    private Converter<Object, byte[]> 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 <T> ValueOperations<String,T> opsForValue(Class<T> c){
        return redisTemplate.opsForValue();
    }
    /**
     * 獲取redis針對列表資料快取操作,元素有序,不唯一
     * @author luxian.zhang
     * @return
     */
    public <T> ListOperations<String,T> opsForList(Class<T> c){
        return redisTemplate.opsForList();
    }
    /**
     * 獲取redis針對集合資料快取操作,元素無序,唯一
     * @author luxian.zhang
     * @return
     */
    public <T> SetOperations<String,T> opsForSet(Class<T> c){
        return redisTemplate.opsForSet();
    }

    /**
     * 獲取redis這對集合資料快取操作,元素有序,唯一
     * @author luxian.zhang
     * @return
     */
    public <T> ZSetOperations<String,T> opsForZSet(Class<T> c){
        return redisTemplate.opsForZSet();
    }

    /**
     * 獲取redis針對物件資料快取操作
     */
    public <T> HashOperations<String,String,T> opsForHash(Class<T> c){
        return redisTemplate.opsForHash();
    }

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

    /**
     * 快取value操作
     * @param k
     * @param v
     */
    public <T> 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> T getValue(Class<T> c, String k) {
        ValueOperations<String, T> 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 <T> boolean cacheSet(String k, T v, long time) {
        String key = KEY_PREFIX_SET + k;
        SetOperations<String, T> valueOps =  redisTemplate.opsForSet();
        valueOps.add(key, v);
        if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 快取set
     * @param k
     * @param v
     */
    public <T> boolean cacheSet(String k, T v) {
        return cacheSet(k, v, -1);
    }

    /**
     * 快取set
     * @param k
     * @param v 把set轉換為陣列
     * @param time
     */
    public <T> boolean cacheSet(String k, T[] v, long time) {
        String key = KEY_PREFIX_SET + k;
        SetOperations<String, T> 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 <T> boolean cacheSet(String k, T[] v) {
        return cacheSet(k, v, -1);
    }

    /**
     * 獲取快取set資料
     * @param c
     * @param k
     */
    public <T> Set<T> getSet(Class<T> c, String k) {
        SetOperations<String, T> setOps = redisTemplate.opsForSet();
        return setOps.members(KEY_PREFIX_SET + k);
    }

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

    /**
     * 快取list
     * @param k
     * @param v
     */
    public <T> boolean cacheList(String k, T v) {
        return cacheList(k, v, -1);
    }

    /**
     * 快取list
     * @param k
     * @param v
     * @param time
     */
    public <T> boolean cacheList(String k, List<T> v, long time) {
        String key = KEY_PREFIX_LIST + k;
        ListOperations<String, T> 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 <T> boolean cacheList(String k, List<T> v) {
       return cacheList(k, v, -1);
    }

    /**
     * 獲取list快取
     * @param c
     * @param k
     * @param start
     * @param end
     */
    public <T> List<T> getList(Class<T> c, String k, long start, long end) {
        ListOperations<String, T> 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;
    }
}