CacheUtil

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.efoxconn.ipebg.common.domain.BaseBean;
import com.efoxconn.ipebg.report.util.EntityUtil;
/**
 * 緩存工具類
 *
 */
@Component("cacheUtil")
public class CacheUtil {
	@Resource(name="jedisPool")
	private JedisPool pool;
	private static final String KEY_PREFIX = "platform_";
	private static final int EXPIRE_TIME= 60 * 60;
	private static final Logger logger = Logger.getLogger(CacheUtil.class);
	/**
	 * 列舉所有key
	 */
	public void keys(){
		Jedis jedis = pool.getResource();
		Set<String> set = jedis.keys(KEY_PREFIX+"*");
		for(String str :set){
			System.out.println(str);
		}
		pool.returnResource(jedis);
	}
	/**
	 * 設置hash
	 * @param key
	 * @param map
	 */
	public void setMap(String key,Map<String,String> map){
		Jedis jedis = pool.getResource();
		jedis.hmset(KEY_PREFIX+key, map);
		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 獲取hash
	 * @param key
	 * @return
	 */
	public Map<String,String> getMap(String key){
		Jedis jedis = pool.getResource();
		Map<String,String> map = jedis.hgetAll(KEY_PREFIX+key);
		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
		return map;
	}
	/**
	 * 獲取字符串
	 * @param key
	 * @return
	 */
	public String get(String key){
		Jedis jedis = pool.getResource();
		String result = jedis.get(KEY_PREFIX+key);
		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
		return result;
	}
	/**
	 * 設置字符串
	 * @param key
	 * @param value
	 */
	public void set(String key,String value){
		Jedis jedis = pool.getResource();
		jedis.set(KEY_PREFIX+key, value);
		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 設置byte[]
	 * @param key
	 * @param bvalue
	 */
	public void bset(String key,byte[] bvalue){
		Jedis jedis = pool.getResource();
		jedis.set((KEY_PREFIX+key).getBytes(), bvalue);
		jedis.expire((KEY_PREFIX+key).getBytes(), EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 獲取byte[]
	 * @param key
	 * @return
	 */
	public byte[] bget(String key){
		Jedis jedis = pool.getResource();
		byte[] result = jedis.get((KEY_PREFIX+key).getBytes());
		jedis.expire((KEY_PREFIX+key).getBytes(), EXPIRE_TIME);
		pool.returnResource(jedis);
		return result;
	}
	/**
	 * 設置BaseBean
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public void setBeanMap(String key,Collection<? extends BaseBean> collection) throws IOException{
		if(collection == null){
			return;
		}
		Jedis jedis = pool.getResource();
		for(BaseBean bean : collection){
			jedis.hset((KEY_PREFIX+key).getBytes(), bean.getId().getBytes(), SerializableByteArrayUtil.serializable2ByteArray(bean));
		}
//		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 獲得BaseBean
	 * @param key
	 * @param value
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public List<?> getBeanMap(String key) throws IOException, ClassNotFoundException{
		Jedis jedis = pool.getResource();
		LinkedList<BaseBean> list = new LinkedList<BaseBean>();
		Map<byte[], byte[]> map = jedis.hgetAll((KEY_PREFIX+key).getBytes());
		if(map.size() == 0){
			return null;
		}
		for(Entry<byte[], byte[]> entry:map.entrySet()){
			list.push((BaseBean)SerializableByteArrayUtil.byteArray2Serializable(entry.getValue()));
		}
		pool.returnResource(jedis);
		return list;
	}
	/**
	 * 設置BaseBean
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public void setBeanMapItem(String key,BaseBean bean) throws IOException{
		if(bean == null){
			return;
		}
		Jedis jedis = pool.getResource();
		jedis.hset((KEY_PREFIX+key).getBytes(), bean.getId().getBytes(), SerializableByteArrayUtil.serializable2ByteArray(bean));
//		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 獲得BaseBean
	 * @param key
	 * @param value
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public BaseBean getBeanMapItem(String key,String id) throws IOException, ClassNotFoundException{
		Jedis jedis = pool.getResource();
		if(TextUtils.isEmpty(id)){
			return null;
		}
		byte[] bytes = jedis.hget((KEY_PREFIX+key).getBytes(), id.getBytes());
		BaseBean bean = (BaseBean) SerializableByteArrayUtil.byteArray2Serializable(bytes);
		pool.returnResource(jedis);
		return bean;
	}
	/**
	 * 設置BaseBean
	 * @param key
	 * @param value
	 * @throws IOException 
	 */
	public void setBeanList(String key,List<? extends BaseBean> list) throws IOException{
		if(list == null){
			return;
		}
		Jedis jedis = pool.getResource();
//		jedis.set(KEY_PREFIX+key, value);
		for(BaseBean bean : list){
			jedis.lpush((KEY_PREFIX+key+":"+bean.getId()).getBytes(), SerializableByteArrayUtil.serializable2ByteArray(bean));
		}
		
		
//		jedis.expire(KEY_PREFIX+key, EXPIRE_TIME);
		pool.returnResource(jedis);
	}
	/**
	 * 獲得BaseBean
	 * @param key
	 * @param value
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public List<BaseBean> getBeanList(String key) throws IOException, ClassNotFoundException{
		Jedis jedis = pool.getResource();
		LinkedList<BaseBean> list = new LinkedList<BaseBean>();
		
		List<byte[]> bytesList = jedis.lrange((KEY_PREFIX+key).getBytes(), 0, jedis.llen(key));
		if(bytesList == null){
			return null;
		}
		for(byte[] bytes : bytesList){
			list.push((BaseBean)SerializableByteArrayUtil.byteArray2Serializable(bytes));
		}
		pool.returnResource(jedis);
		return list;
	}
	/**
	 * 刪除key
	 * @param key
	 */
	public void del(String key){
		Jedis jedis = pool.getResource();
		long s = jedis.del(KEY_PREFIX+key);
		pool.returnResource(jedis);
	}
	/**
	 * 將數據對接存放
	 * @param key
	 * @param obj
	 * @param expireSeconds 超時時間(秒)
	 * @throws IOException
	 */
	public void setObject(String key,Object obj,int expireSeconds) throws IOException{
		if(StringUtils.isEmpty(key)||StringUtils.isBlank(key)){
			logger.error("對象緩存至redis失敗,因為key="+key);
			return;
		}
		if(obj==null){
			logger.error("對象緩存至redis失敗,因為obj="+obj);
			return;
		}
		
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis==null){
				logger.error("連接redis連接失敗");
				return;
			}
			if(!jedis.isConnected()){
				logger.error("獲取的redis連接狀態已關閉");
				return;
			}
			String _k=KEY_PREFIX+DateUtil.getNowTime("dd")+key;
			byte[] bs=EntityUtil.toByteArray(obj);		
			jedis.setex(_k.getBytes(),expireSeconds,bs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(jedis!=null){
				pool.returnResource(jedis);
			}
	    }

	}
	public <T> T getObject(String key) throws IOException{
		if(true||StringUtils.isEmpty(key)||StringUtils.isBlank(key)){
			logger.error("獲取redis失敗,因為key="+key);
			return null;
		}
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis==null){
				logger.error("連接redis連接失敗");
				return null;
			}
			if(!jedis.isConnected()){
				logger.error("獲取的redis連接狀態已關閉");
				return null;
			}
			String _k=KEY_PREFIX+DateUtil.getNowTime("dd")+key;
			byte[] bs=jedis.get(_k.getBytes());			
			if(bs==null){
				return null;
			}
			return (T)EntityUtil.toObject(bs);
		} catch (Exception e) {
			logger.error("從redis里獲取對象失敗,key="+key);		
		}finally {
			if(jedis!=null){
				pool.returnResource(jedis);
			}
	    }
		return null;
	}
	/**
	 * 刪除所有key
	 */
	public String delKeys(){
		Jedis jedis = null;
		try{
			jedis = pool.getResource();
			Set<String> set = jedis.keys(KEY_PREFIX+"*");
			for(String str :set){
				jedis.del(str.getBytes());
			}
			pool.returnResource(jedis);
		}catch(Exception e){
			return "1";
		}
		return "0";
	}
	/**
	 * 列舉所有key
	 */
	public List<String> getKeys(){
		Jedis jedis = null;
		List<String> keyList=null;
		try{
			jedis = pool.getResource();
			keyList=new ArrayList<String>();
			Set<String> set = jedis.keys(KEY_PREFIX+"*");
			for(String str :set){
				keyList.add(str);
			}
			pool.returnResource(jedis);
		}catch(Exception e){
			return keyList;
		}
		return keyList;
	}
	/**
	 * 刪除key
	 * @param key
	 */
	public String delKey(String key){
		Jedis jedis = null;
		List<String> keyList=null;
		try{
			jedis = pool.getResource();
			long s = jedis.del(key.getBytes());
			pool.returnResource(jedis);
		}catch(Exception e){
			return "1";
		}
		return "0";
	}
}

猜你喜欢

转载自com-niu.iteye.com/blog/2356018