redis Jedis序列化自定义存储list对象和map数据

阅读更多
1,redis缓存配置类
public class RedisCache {
	protected static Logger logger = Logger.getLogger(RedisCache.class);
	public final static String VIRTUAL_COURSE_PREX = "_lc_vc_";
	
	
	private RedisCacheConfig redisCacheConfig;
	private JedisPool jedisPool = null;
	
	public RedisCacheConfig getRedisCacheConfig() {
		return redisCacheConfig;
	}

	public void setRedisCacheConfig(RedisCacheConfig redisCacheConfig) {
		this.redisCacheConfig = redisCacheConfig;
	}

	public RedisCache(){
		
	}
	
	/**
	 * 初始化Redis连接池
	 */
	private void initialPool(){
		JedisPoolConfig poolConfig = redisCacheConfig.getPoolConfig();
		String[] serverArray = redisCacheConfig.getServers().split(",");
		for(int i = 0; i < serverArray.length; i++){
			try {
				JedisPoolConfig config = new JedisPoolConfig();
				config.setMaxTotal(poolConfig.getMaxTotal());
				config.setMaxIdle(poolConfig.getMaxIdle());
				config.setMaxWaitMillis(poolConfig.getMaxWaitMillis());
				config.setTestOnBorrow(poolConfig.getTestOnBorrow());
				config.setTestOnReturn(poolConfig.getTestOnReturn());
				
				jedisPool = new JedisPool(config, serverArray[i], redisCacheConfig.getPort(), redisCacheConfig.getTimeout());
				break;
			} catch (Exception e) {
				logger.error("initialPool create JedisPool(" + serverArray[i] + ") error : "+e);
			}
		}
		
	}
	
	/**
	 * 在多线程环境同步初始化
	 */
	private synchronized void poolInit() {
		if (jedisPool == null) {  
			initialPool();
		}
	}
 
	 
	/**
	 * 同步获取Jedis实例
	 * @return Jedis
	 */
	public synchronized Jedis getJedis() {
		if (jedisPool == null) {
			poolInit();
		}
		Jedis jedis = null;
		try {
			if (jedisPool != null) {
				jedis = jedisPool.getResource();
				jedis.auth(redisCacheConfig.getAuth());
			}
		} catch (Exception e) {
			logger.error("Get jedis error : "+e);
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return jedis;
	}
	
	/**
	 * 释放jedis资源
	 * @param jedis
	 */
	public void returnResource(final Jedis jedis) {
		if (jedis != null && jedisPool !=null) {
			jedisPool.returnResource(jedis);
		}
	}

	/**
	 * 得到Key
	 * @param key
	 * @return
	 */
	public String buildKey(String key){
		return VIRTUAL_COURSE_PREX + key;
	}
	/**
	 * 设置 String
	 * @param key
	 * @param value
	 */
	public void setString(String key ,String value){
		try {
			value = StringUtil.isNullOrEmpty(value) ? "" : value;
			getJedis().set(buildKey(key),value);
		} catch (Exception e) {
			logger.error("Set key error : "+e);
		}
	}
	 
	/**
	 * 设置 过期时间
	 * @param key
	 * @param seconds 以秒为单位
	 * @param value
	 */
	public void setString(String key ,int seconds,String value){
		try {
			value = StringUtil.isNullOrEmpty(value) ? "" : value;
			getJedis().setex(buildKey(key), seconds, value);
		} catch (Exception e) {
			logger.error("Set keyex error : "+e);
		}
	}
	 
	/**
	 * 获取String值
	 * @param key
	 * @return value
	 */
	public String getString(String key){
		String bKey = buildKey(key);
		if(getJedis() == null || !getJedis().exists(bKey)){
			return null;
		}
		return getJedis().get(bKey);
	}
	/**
	 * 设置 list
	 * @param 
	 * @param key
	 * @param value
	 */
	public  void setList(String key ,List list){
		try {
			getJedis().set(key.getBytes(),ObjectTranscoder.serialize(list));
		} catch (Exception e) {
			logger.error("Set key error : "+e);
		}
	}
	/**
	 * 获取list
	 * @param 
	 * @param key
	 * @return list
	 */
	public  List getList(String key){
		String bKey = buildKey(key);
		if(getJedis() == null || !getJedis().exists(key.getBytes())){
			return null;
		}
		byte[] in = getJedis().get(key.getBytes());  
        List list = (List) ObjectTranscoder.deserialize(in);  
		return list;
	}
	/**
	 * 设置 map
	 * @param 
	 * @param key
	 * @param value
	 */
	public  void setMap(String key ,Map map){
		try {
			getJedis().set(key.getBytes(),ObjectTranscoder.serialize(map));
		} catch (Exception e) {
			logger.error("Set key error : "+e);
		}
	}
	/**
	 * 获取list
	 * @param 
	 * @param key
	 * @return list
	 */
	public  Map getMap(String key){
		String bKey = buildKey(key);
		if(getJedis() == null || !getJedis().exists(key.getBytes())){
			return null;
		}
		byte[] in = getJedis().get(key.getBytes());  
		Map map = (Map) ObjectTranscoder.deserialize(in);  
		return map;
	}
}

2,spring配置

	
		
	
	
		${redis.servers}
		${redis.port}
		${redis.auth}
		${redis.pool.timeout}
		
	
	
		${redis.pool.maxTotal}
		${redis.pool.maxIdle}
		${redis.pool.maxWait}
		${redis.pool.testOnBorrow}
		${redis.pool.testOnReturn}
	

3,序列化工具类
public class ObjectTranscoder {
	public static byte[] serialize(Object value) {  
        if (value == null) {  
            throw new NullPointerException("Can't serialize null");  
        }  
        byte[] rv=null;  
        ByteArrayOutputStream bos = null;  
        ObjectOutputStream os = null;  
        try {  
            bos = new ByteArrayOutputStream();  
            os = new ObjectOutputStream(bos);  
            os.writeObject(value);  
            os.close();  
            bos.close();  
            rv = bos.toByteArray();  
        } catch (IOException e) {  
            throw new IllegalArgumentException("Non-serializable object", e);  
        } finally {  
        	try {
	        	 if(os!=null)os.close();
	        	 if(bos!=null)bos.close();
       	 	}catch (Exception e2) {
       		 e2.printStackTrace();
			}  
        }  
        return rv;  
    }  

    public static Object deserialize(byte[] in) {  
        Object rv=null;  
        ByteArrayInputStream bis = null;  
        ObjectInputStream is = null;  
        try {  
            if(in != null) {  
                bis=new ByteArrayInputStream(in);  
                is=new ObjectInputStream(bis);  
                rv=is.readObject();  
                is.close();  
                bis.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();
         }finally {  
        	 try {
	        	 if(is!=null)is.close();
	        	 if(bis!=null)bis.close();
        	 } catch (Exception e2) {
        		 e2.printStackTrace();
 			 }
         }
        return rv;  
    }  
}

你可能感兴趣的:(redis,java,spring)