Java Redis实现session共享

 1 package com.hzlg.ui.util;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Component;
 7 
 8 import redis.clients.jedis.Jedis;
 9 import redis.clients.jedis.JedisPool;
10 @Component
11 public class RedisUtil {
12    
13     /**
14      * redis 连接池,这里jedisPool我们再之前spring配置中配置好了,交给spring管理,这里可以自动注入
15      */
16     @Autowired
17     private JedisPool jedisPool;
18  
19     public void setPool(JedisPool jedisPool) {
20         this.jedisPool = jedisPool;
21     }
22     /**
23      * 获取jedis
24      * @return
25      */
26     public Jedis getResource(){
27         Jedis jedis =null;
28         try {
29             jedis =jedisPool.getResource();
30         } catch (Exception e) {
31             CommonUtils.logger.info(e);
32             CommonUtils.logger.info("can't  get  the redis resource");
33         }
34         return jedis;
35     }
36     /**
37      * 关闭连接
38      * @param jedis
39      */
40     public void disconnect(Jedis jedis){
41         jedis.disconnect();
42     }
43     /**
44      * 将jedis 返还连接池
45      * @param jedis
46      */
47     public void returnResource(Jedis jedis){
48         if(null != jedis){
49             try {
50                 jedisPool.returnResource(jedis);
51             } catch (Exception e) {
52                 CommonUtils.logger.info(e);
53                 CommonUtils.logger.info("can't return jedis to jedisPool");
54             }
55         }
56     }
57     /**
58      * 无法返还jedispool,释放jedis客户端对象,
59      * @param jedis
60      */
61     public void brokenResource(Jedis jedis){
62         if (jedis!=null) {
63             try {
64                 jedisPool.returnBrokenResource(jedis);
65             } catch (Exception e) {
66                 CommonUtils.logger.info(e);
67                 CommonUtils.logger.info("can't release jedis Object");
68             }
69         }
70     }
71 }
View Code
package com.hzlg.ui.service;

import java.util.Map;

public interface RedisCacheStorageService<K,V> {
    /**
     * 在redis数据库中插入 key  和value
     * @param key
     * @param value
     * @return
     */
    boolean set(K key,V value);
    /**
     * 在redis数据库中插入 key  和value 并且设置过期时间
     * @param key
     * @param value
     * @param exp 过期时间
     * @return
     */
    boolean set(K key, V value, int exp);
    /**
     * 根据key 去redis 中获取value
     * @param key
     * @return
     */
    V get(K key,Object object);
    /**
     * 删除redis库中的数据
     * @param key
     * @return
     */
    boolean remove(K key);
    /**
     * 设置哈希类型数据到redis 数据库
     * @param cacheKey 可以看做一张表
     * @param key   表字段
     * @param value
     * @return
     */
    boolean hset(String cacheKey,K key,V value);
    /**
     * 获取哈希表数据类型的值
     * @param cacheKey
     * @param key
     * @return
     */
    V hget(String cacheKey,K key,Object object);
    /**
     * 获取哈希类型的数据
     * @param cacheKey
     * @return
     */
    Map<K,V> hget(String cacheKey,Object object);
    /**
     * 该条记录在redis中是否存在
     * **/
    boolean exists(String sessionid);
}
package com.hzlg.ui.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.hzlg.ui.entity.UserInfo;
import com.hzlg.ui.service.RedisCacheStorageService;
import com.hzlg.ui.util.CommonUtils;
import com.hzlg.ui.util.RedisUtil;

@Service("redisCacheStorageServiceImpl")
public class RedisCacheStorageServiceImpl<V> implements RedisCacheStorageService<String,V>{
    
    /**
     * 默认过时时间
     */
    private static final int EXPRIE_TIME =3600*24;
 
    /**
     * 获取Jedis相关操作
     */
    @Autowired
    private RedisUtil redisUtil;
 
    @Override
    public boolean set(String key, V value) {
        
        return set(key,value,EXPRIE_TIME);
    }
 
    @Override
    public boolean set(String key, V value, int exp) {
        Jedis jedis=null;
        if(StringUtils.isEmpty(key)){
            return  false;
        }
        try {
            //获取jedis对象
            jedis= redisUtil.getResource();
            //使用对象转换为Json格式插入redis
            JSONObject json = JSONObject.fromObject(value);//将java对象转换为json对象
            String jsonValue = json.toString();//将json对象转换为json字符串
            jedis.setex(key,exp,jsonValue);
        }catch (Exception e){
            CommonUtils.logger.info(e);
            //释放jedis对象
            redisUtil.brokenResource(jedis);
            CommonUtils.logger.info("client can't connect server");
            return  false;
        }finally {
            redisUtil.returnResource(jedis);//返还连接池
            return true;
        }
    }
 
    @Override
    public V get(String key,Object object) {
        Jedis jedis=null;
        V v=null;
        if(StringUtils.isEmpty(key)){
            CommonUtils.logger.info("redis取值,key为空");
            return  null;
        }
        try{
            jedis=redisUtil.getResource();  //获取连接
            String jsonValue=jedis.get(key);   //从redis得到值,得到的是json字符串,因为我们之前插入的时候是使用的json字符串
            if(StringUtils.isEmpty(jsonValue)){
                return  null;
            }
            JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
            v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为你想要的java对象
            return v;
       }catch (Exception e){
           CommonUtils.logger.info(e);
        //释放jedis对象
            if(jedis!=null){
                redisUtil.brokenResource(jedis);
            }
            CommonUtils.logger.info("client can't get value");
        return  null;
       }finally {
        //返还连接池
        redisUtil.returnResource(jedis);
 
    }
 
    }
 
    @Override
    public boolean remove(String key) {
        Jedis jedis=null;
        try{
            jedis=redisUtil.getResource();
            if(StringUtils.isEmpty(key)){
                CommonUtils.logger.info("redis取值,key为空");
                return  false;
            }
             jedis.del(key);
        }catch (Exception e) {
            CommonUtils.logger.info(e);
            //释放jedis对象
            if(jedis!=null){
                redisUtil.brokenResource(jedis);
            }
            CommonUtils.logger.info("  del fail from redis");
            return false;
 
        }finally{
            //返还连接池
            redisUtil.returnResource(jedis);
            return true;
        }
 
 
 
    }
 
    @Override
    public boolean hset(String cacheKey, String key, V value) {
        Jedis jedis =null;
        //将key 和value  转换成 json 对象
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串
        JSONObject json2 = JSONObject.fromObject(value);//将java对象转换为json对象
        String jsonValue = json2.toString();//将json对象转换为json字符串
        //操作是否成功
        boolean isSucess =true;
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty");
            return false;
        }
        try {
            jedis =redisUtil.getResource();
            //执行插入哈希
            jedis.hset(jCacheKey, key, jsonValue);
        } catch (Exception e) {
            CommonUtils.logger.info("client can't connect server");
            isSucess =false;
            if(null !=jedis){
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
            return false;
        }finally{
            if (isSucess) {
                //返还连接池
                redisUtil.returnResource(jedis);
            }
            return true;
        }
    }
 
    @Override
    public V hget(String cacheKey, String key,Object object) {
        Jedis jedis =null;
        V v =null;
 
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串
 
 
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty");
            return null;
        }
        try {
            //获取客户端对象
            jedis =redisUtil.getResource();
            //执行查询
            String jsonValue =  jedis.hget(jCacheKey, key);
            //判断值是否非空
            if(StringUtils.isEmpty(jsonValue)){
                return null;
            }else{
 
                JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
 
                v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
 
            }
            //返还连接池
            redisUtil.returnResource(jedis);
        } catch (JedisException e) {
            CommonUtils.logger.info("client can't connect server");
            if(null !=jedis){
                //redisUtil 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return v;
    }
 
    @Override
    public Map<String, V> hget(String cacheKey,Object object) {
 
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为字符串
        //非空校验
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty!");
            return null;
        }
        Jedis jedis =null;
        Map<String,V> result =null;
        V v=null;
        try {
            jedis =redisUtil.getResource();
            //获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String
            Map<String,String> map = jedis.hgetAll(jCacheKey);
 
            if(null !=map){
                for(Map.Entry<String, String> entry : map.entrySet()){
                    if(result ==null){
                        result =new HashMap<String,V>();
                    }
 
                    JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象
                    v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
 
                    result.put(entry.getKey(), v);
                }
            }
        } catch (JedisException e) {
            CommonUtils.logger.info("client can't connect server");
            if(null !=jedis){
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return result;
    }

    
    @Override
    public boolean exists(String sessionid) {
        UserInfo userInfo=(UserInfo) get(sessionid,new UserInfo());
        if(userInfo!=null){
            return true;
        }
        return false;
    }
}
View Code
package com.hzlg.ui.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.hzlg.ui.entity.UserInfo;
import com.hzlg.ui.service.RedisCacheStorageService;
import com.hzlg.ui.util.CommonUtils;
import com.hzlg.ui.util.RedisUtil;

@Service("redisCacheStorageServiceImpl")
public class RedisCacheStorageServiceImpl<V> implements RedisCacheStorageService<String,V>{
    
    /**
     * 默认过时时间
     */
    private static final int EXPRIE_TIME =3600*24;
 
    /**
     * 获取Jedis相关操作
     */
    @Autowired
    private RedisUtil redisUtil;
 
    @Override
    public boolean set(String key, V value) {
        
        return set(key,value,EXPRIE_TIME);
    }
 
    @Override
    public boolean set(String key, V value, int exp) {
        Jedis jedis=null;
        if(StringUtils.isEmpty(key)){
            return  false;
        }
        try {
            //获取jedis对象
            jedis= redisUtil.getResource();
            //使用对象转换为Json格式插入redis
            JSONObject json = JSONObject.fromObject(value);//将java对象转换为json对象
            String jsonValue = json.toString();//将json对象转换为json字符串
            jedis.setex(key,exp,jsonValue);
        }catch (Exception e){
            CommonUtils.logger.info(e);
            //释放jedis对象
            redisUtil.brokenResource(jedis);
            CommonUtils.logger.info("client can't connect server");
            return  false;
        }finally {
            redisUtil.returnResource(jedis);//返还连接池
            return true;
        }
    }
 
    @Override
    public V get(String key,Object object) {
        Jedis jedis=null;
        V v=null;
        if(StringUtils.isEmpty(key)){
            CommonUtils.logger.info("redis取值,key为空");
            return  null;
        }
        try{
            jedis=redisUtil.getResource();  //获取连接
            String jsonValue=jedis.get(key);   //从redis得到值,得到的是json字符串,因为我们之前插入的时候是使用的json字符串
            if(StringUtils.isEmpty(jsonValue)){
                return  null;
            }
            JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
            v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为你想要的java对象
            return v;
       }catch (Exception e){
           CommonUtils.logger.info(e);
        //释放jedis对象
            if(jedis!=null){
                redisUtil.brokenResource(jedis);
            }
            CommonUtils.logger.info("client can't get value");
        return  null;
       }finally {
        //返还连接池
        redisUtil.returnResource(jedis);
 
    }
 
    }
 
    @Override
    public boolean remove(String key) {
        Jedis jedis=null;
        try{
            jedis=redisUtil.getResource();
            if(StringUtils.isEmpty(key)){
                CommonUtils.logger.info("redis取值,key为空");
                return  false;
            }
             jedis.del(key);
        }catch (Exception e) {
            CommonUtils.logger.info(e);
            //释放jedis对象
            if(jedis!=null){
                redisUtil.brokenResource(jedis);
            }
            CommonUtils.logger.info("  del fail from redis");
            return false;
 
        }finally{
            //返还连接池
            redisUtil.returnResource(jedis);
            return true;
        }
 
 
 
    }
 
    @Override
    public boolean hset(String cacheKey, String key, V value) {
        Jedis jedis =null;
        //将key 和value  转换成 json 对象
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串
        JSONObject json2 = JSONObject.fromObject(value);//将java对象转换为json对象
        String jsonValue = json2.toString();//将json对象转换为json字符串
        //操作是否成功
        boolean isSucess =true;
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty");
            return false;
        }
        try {
            jedis =redisUtil.getResource();
            //执行插入哈希
            jedis.hset(jCacheKey, key, jsonValue);
        } catch (Exception e) {
            CommonUtils.logger.info("client can't connect server");
            isSucess =false;
            if(null !=jedis){
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
            return false;
        }finally{
            if (isSucess) {
                //返还连接池
                redisUtil.returnResource(jedis);
            }
            return true;
        }
    }
 
    @Override
    public V hget(String cacheKey, String key,Object object) {
        Jedis jedis =null;
        V v =null;
 
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串
 
 
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty");
            return null;
        }
        try {
            //获取客户端对象
            jedis =redisUtil.getResource();
            //执行查询
            String jsonValue =  jedis.hget(jCacheKey, key);
            //判断值是否非空
            if(StringUtils.isEmpty(jsonValue)){
                return null;
            }else{
 
                JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
 
                v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
 
            }
            //返还连接池
            redisUtil.returnResource(jedis);
        } catch (JedisException e) {
            CommonUtils.logger.info("client can't connect server");
            if(null !=jedis){
                //redisUtil 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return v;
    }
 
    @Override
    public Map<String, V> hget(String cacheKey,Object object) {
 
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为字符串
        //非空校验
        if(StringUtils.isEmpty(jCacheKey)){
            CommonUtils.logger.info("cacheKey is empty!");
            return null;
        }
        Jedis jedis =null;
        Map<String,V> result =null;
        V v=null;
        try {
            jedis =redisUtil.getResource();
            //获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String
            Map<String,String> map = jedis.hgetAll(jCacheKey);
 
            if(null !=map){
                for(Map.Entry<String, String> entry : map.entrySet()){
                    if(result ==null){
                        result =new HashMap<String,V>();
                    }
 
                    JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象
                    v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
 
                    result.put(entry.getKey(), v);
                }
            }
        } catch (JedisException e) {
            CommonUtils.logger.info("client can't connect server");
            if(null !=jedis){
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return result;
    }

    
    @Override
    public boolean exists(String sessionid) {
        UserInfo userInfo=(UserInfo) get(sessionid,new UserInfo());
        if(userInfo!=null){
            return true;
        }
        return false;
    }
}
View Code

applicationContext.xml配置

<context:property-placeholder location="classpath*:/application.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="500"/><!-- 最大连接数 -->
        <property name="maxIdle" value="100"/><!-- 最大闲置 -->
        <property name="minIdle" value="10"/><!-- 最小闲置 -->
        <property name="maxWaitMillis" value="5000"/><!-- 最大等待 -->
        <property name="testOnBorrow" value="true"/><!-- 可以获取 -->
    </bean>
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="2" value="6379"/><!-- 端口 -->
        <constructor-arg index="3" value="5000"/><!-- 超时 -->
        <constructor-arg index="1" value="127.0.0.1"/><!-- Redis IP地址 -->
        <constructor-arg index="4" value="123456"/><!-- 密码 -->
    </bean>
View Code

application.properties

#-------Redis--------
redis.pool.maxTotal=1000
redis.pool.maxIdle=200
redis.pool.maxWaitMillis=2000
redis.pool.testOnBorrow=true
redis.host=127.0.0.1
redis.password=123456
redis.port=6379

 所需jar包

commons-pool2-2.4.2-javadoc.jar,commons-pool2-2.4.2.jar,jedis-2.7.2.jar,spring-data-redis-2.0.9.RELEASE.jar,spring-session-1.2.1.RELEASE.jar

posted @ 2018-08-21 16:07  枫沫  阅读(11401)  评论(0编辑  收藏  举报