redisUtil

package com.gnet.common;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;


import com.gnet.common.MailUtil.mailRen;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
/**
 * 
 * redis 緩存管理工具類
 *
 */
public class RedisCache {
private static String cacheIp;
private static int cachePort;
private static JedisPool jedisPool = null;
static {
initialPool();
}
/**
     * 初始化Redis連接池
     */
private static void initialPool() {
try {
String[] redisUrl = ResourceBundle.getBundle("config/global").getString("redisUrl").split(":");
cacheIp = redisUrl[0].trim();
cachePort = Integer.valueOf(redisUrl[1].trim());
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(200);
config.setMaxIdle(5);
config.setMaxWaitMillis(1000);
config.setTestOnBorrow(true);
//連接耗盡時是否阻塞, false報異常,ture阻塞直到超時, 默認true
config.setBlockWhenExhausted(true);
jedisPool = new JedisPool(config, cacheIp, cachePort, 100000);
} catch (Exception e) {
if(!MailUtil.sendEmail("緊急求助-教育系統", cacheIp+"\nredis 需要申請資源\n redis頂不住了!!!"+e.toString(),new String[]{mailRen.李來星.value,mailRen.王春鑫.value,mailRen.桑慧娜.value},new String[]{mailRen.尹海平.value})){
MailUtil.sendEmail("緊急求助-教育系統", cacheIp+"\nredis 需要申請資源\n redis頂不住了!!!"+e.toString(),new String[]{mailRen.李來星.value,mailRen.王春鑫.value,mailRen.桑慧娜.value},new String[]{mailRen.尹海平.value});
}
/*
* try{ //如果第一個IP異常,則訪問第二個IP JedisPoolConfig config = new
* JedisPoolConfig(); config.setMaxTotal(MAX_ACTIVE);
* config.setMaxIdle(MAX_IDLE); config.setMaxWaitMillis(MAX_WAIT);
* config.setTestOnBorrow(TEST_ON_BORROW); jedisPool = new
* JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT);
* }catch(Exception e2){

* }
*/
}
}
@SuppressWarnings("unused")
private static void initialPool_bak() {
String[] redisUrl = ResourceBundle.getBundle("config/global").getString("redisUrl").split(",");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si ;
for(String urlFor : redisUrl){
cacheIp = urlFor.split(":")[0].trim();
cachePort = Integer.valueOf(urlFor.split(":")[1].trim());
si = new JedisShardInfo(cacheIp, cachePort);
shards.add(si);
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(300);
config.setMaxIdle(5);
config.setMaxWaitMillis(20);
config.setTestOnBorrow(true);
//連接耗盡時是否阻塞, false報異常,ture阻塞直到超時, 默認true
config.setBlockWhenExhausted(true);
// jedisPool = new ShardedJedisPool(config, shards);
}
/**
* 在多線程環境同步初始化
*/
private static synchronized void poolInit() {
if (jedisPool == null) {
initialPool();
}
}
    
    /**
     * 同步獲取Jedis實例
     * @return Jedis
     */
public synchronized static Jedis getJedis() {
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
}
} catch (Exception e) {
MailUtil.sendEmail("緊急求助-教育系統-redis異常", cacheIp+" redis 運行異常</br> redis頂不住了!!!</br>getMaxBorrowWaitTimeMillis:"+
jedisPool.getMaxBorrowWaitTimeMillis()+
"</br>getMeanBorrowWaitTimeMillis:"+jedisPool.getMeanBorrowWaitTimeMillis()+
"</br>getNumActive:"+jedisPool.getNumActive()+
"</br>getNumIdle:"+jedisPool.getNumIdle()+
"</br>NumWaiters:"+jedisPool.getNumWaiters()+
e.toString(),new String[]{mailRen.尹海平.value},null);
} finally {
returnResource(jedis);
}
return jedis;
}
    
    /**
     * 釋放jedis資源
     * @param jedis
     */
    @SuppressWarnings("deprecation")
public static Boolean returnResource(final Jedis jedis) {
    try{
       if (jedis != null && jedisPool !=null) {
           jedisPool.returnResource(jedis);
//            jedisPool.returnBrokenResource(jedis);
       }
       return true;
    }catch(Exception e){
    return false;
    }
    }

/**
* 刪除String類型的緩存
* @param key
* @return
*/
public static Boolean delCacheByKey(String key){
if(key==null){
return null;
}
return getJedis().del(key) != 0 ? true : false;
}

/**
* 刪除String類型的緩存
* @param key
* @return
*/
public static Boolean exists(String key){
if(key==null){
return null;
}
return getJedis().exists(key);
}

/**
* 設置String類型的緩存
* @param key
* @param value
* @return
*/
public static Boolean setString(String key,String value){
if(key==null||value==null){
return null;
}
return getJedis().set(key, value).equals("OK") ? true : false;
}

/**
* 返回String類型的緩存
* @param key
* @param value
* @return
*/
public static String getString(String key){
if(key==null){
return null;
}
return getJedis().get(key);
}
/**
* 獲取多個key的值
* @param keys
* @return
*/
// public static List<String> getStringByKeys(String... keys){
// if(keys==null){
// return null;
// }
// return getJedis().mget(keys);
// }
/**
* 根據key遞增value值,num增加多大的數
* @param key
* @param num
* @return
*/
public static Long increasing(String key,int num){
if(key==null){
return null;
}
return getJedis().incrBy(key, num);
}
/**
* 根據key遞減value值,num減少多大的數
* @param key
* @param num
* @return
*/
public static Long diminishing(String key,int num){
if(key==null){
return null;
}
return getJedis().decrBy(key, num);
}
/**
* 設置list類型的緩存
* @param key
* @param values
* @return
*/
public static Boolean setList(String key,String... values){
if(key==null||values==null){
return null;
}
return getJedis().rpush(key, values)!= 0 ? true : false;
}
/**

* @param key
* @param values
* @return
*/
public static Boolean delList(String key,String value){
if(key==null||value==null){
return null;
}
List<String> list = getJedis().lrange(key,0,-1);
int count = -1;
for(int i = 0 ;i<list.size();i++){
if(list.get(i).equals(value)){
count=i;
break;
}
}
if(count==-1){
return false;
}
getJedis().lrem(key, count, value);
return true;
}
/**
* 設置list類型的緩存
* @param key
* @param values
* @return
*/
public static Boolean setList(String key,List<String> value){
if(key==null||value==null){
return null;
}
String[] StringArray = (String[]) value.toArray();
delCacheByKey(key);
return getJedis().rpush(key, StringArray)!= 0 ? true : false;
}

/**
* 返回list值
* @param key
* @return
*/
public static List<String> getList(String key){
if(key==null){
return null;
}
return getJedis().lrange(key,0,-1);
}
/**
* 判斷list值是否存在
* @param key
* @return
*/
public static String listIsExists(String key,String value){
if(key==null||value==null){
return null;
}
for(String str : getJedis().lrange(key,0,-1)){
if(str.equals(value)){
return str;
}
}
return null;
}
/**
* 返回list長度
* @param key
* @return
*/
public static Long getListSize(String key){
if(key==null){
return null;
}
return getJedis().llen(key);
}

/**
* 設置map值
* @param key
* @param mapParam
* @return
*/
public static String setMap(String key,Map<String,String> mapParam){
if(key==null||mapParam==null){
return null;
}
return getJedis().hmset(key, mapParam);
}
/**
* 刪除map值
* @param key
* @param mapParam
* @return
*/
public static Boolean delMapKey(String key,String... fields){
if(key==null||fields==null){
return null;
}
return getJedis().hdel(key, fields)>0?true:false;
}
/**
* map值必需是整形,在原值增加num值
* @param key
* @param mapKey
* @param num
* @return 
*/
public static boolean updataMapValue(String key,String mapKey,long num){
if(key==null||mapKey==null){
return false;
}
try{
getJedis().hincrBy(key, mapKey, num);
return true;
}catch(Exception e){
return false;
}
}

/**
* 獲取Map
* @param key
* @return
*/
public static Map<String, String> getMap(String key){
if(key==null){
return null;
}
return getJedis().hgetAll(key);
}
/**
* 獲取所有map的key值
* @param key
* @return
*/
public static Set<String> getMapKeys(String key){
if(key==null){
return null;
}
return getJedis().hkeys(key);
}
/**
* 獲取map的值,根據cache的key和map的key
* @param key
* @return
*/
public static String getMapValueByKey(String key,String mapKey){
if(key==null||mapKey==null){
return null;
}
return getJedis().hget(key, mapKey);
}
/**
* 獲取map的值,根據cache的key和map的key可以多個KEY
* @param key
* @return
*/
public static List<String> getMapValueByKeys(String key,String... mapKeys){
if(key==null||mapKeys==null){
return null;
}
return getJedis().hmget(key, mapKeys);
}
/**
* 獲取map的個數
* @param key
* @return
*/
public static Long getMapNumByKey(String key){
if(key==null){
return null;
}
return getJedis().hlen(key);
}
/**
* 獲取map的key是否存在
* @param key
* @return
*/
public static Boolean getMapKeyIsExists(String key,String field){
if(key==null||field==null){
return null;
}
return getJedis().hexists(key, field);
}

/**
* 添加隊列
* @param key cache的key
* @param score 權重這個不能和之前的重複,重複會覆蓋之前的數據。回去結果的時候會根據這個排序的。
* @param member 消息
* @return
*/
public static boolean setZadd(String key,Double score,String member){
if(key==null||score==null||member==null){
return false;
}
return getJedis().zadd(key, score, member)==0?false:true;
}
/**
* 獲取隊列
* @param key cache的key
* @param start 開始位置
* @param end 結束位置
* @return
*/
public static Object[] getZrange(String key,int start,int end){
if(key==null){
return null;
}
return getJedis().zrange(key, start, end).toArray();
}
/**
* 這個自增隊列使用
* @param key
* @return
*/
public static Long incrementNum(String key){
if(key==null){
return null;
}
return getJedis().incr(key);
}
/**
* 根據cache的key和隊列的值刪除元素
* @param key
* @param members
* @return
*/
public static Long delZadd(String key,String... members){
if(key==null||members==null){
return null;
}
return getJedis().zrem(key, members);
}
/**
* 根據cache的key和隊列的分值開始和結束區間刪除
* @param key
* @param start
* @param end
* @return
*/
public static Long delZadd(String key,Double start,Double end){
if(key==null){
return null;
}
return getJedis().zremrangeByScore(key, start, end);
}

/**
* 設置set值
* @param key
* @param members
* @return
*/
public static Boolean setSet(String key,String... members){
if(key==null||members==null){
return null;
}
return getJedis().sadd(key, members)!=0?true:false;
}
/**
* 判斷set值是否存在
* @param key
* @param value
* @return
*/
public static Boolean setIsExists(String key,String value){
if(key==null||value==null){
return false;
}
return getJedis().sismember(key, value);
}

/**
* 返回key的所有set值
* @param key
* @return
*/
public static Set<String> getSet(String key){
if(key==null){
return null;
}
return getJedis().smembers(key);
}
/**
* 獲取系統運行狀態
* @param keyword
* @return
*/
public static String info(String keyword){
if(keyword==null){
return getJedis().info();
}else{
return getJedis().info(keyword);
}
// Collection<Jedis> jedisList = getJedis().getAllShards();
// StringBuffer info = new StringBuffer();
// for(Jedis jedisFor : jedisList){
// info.append(jedisFor.info());
// }
// return info.toString();
}
/**
* 獲取所有數據
* @param keyword
* @return
*/
public static Set<String> getRedisAllKeys(String keyword){
if(keyword==null||keyword.trim().isEmpty()){
return getJedis().hkeys("*");
}else{
return getJedis().hkeys(keyword);
}

}
/**
* 存byte
* @param key
* @param value
*/
public static void set(String key, Object value) {
if(key!=null||value!=null){
getJedis().set(key.getBytes(), SerializeUtil.serialize(value));
}
}
/**
* 取byte
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
T value = null;
byte[] byteValue = getJedis().get(key.getBytes());
value = (T) SerializeUtil.unserialize(byteValue);
return value;
}

public static void main(String[] args) {
// DRFServiceRestCustomized s= new DRFServiceRestCustomized("114.112.90.40:10107", "0_0_0");
// System.out.println(JSON.toJSONString(s.insert(drfDbid, "[{\"TableName\":\"主任務表\",\"ValueList\":[[{\"ColumnName\":\"名稱\",\"ColumnValue\":\"測試完發\"},{\"ColumnName\":\"開始時間\",\"ColumnValue\":\"2016-03-22 00:00:00\"},{\"ColumnName\":\"結束時間\",\"ColumnValue\":\"2016-03-29 00:00:00\"},{\"ColumnName\": \"使用地區\",\"ColumnValue\": \"寧夏回族,固原市,隆德縣教育局\"},{\"ColumnName\": \"上傳人userId\",\"ColumnValue\": \"123\"},{\"ColumnName\": \"上傳人姓名\",\"ColumnValue\": \"123\"}]]}]", new InsertConfig(0, false,false).getJson())));

// RedisCache r = new RedisCache();
// Map<String,String> map = new HashMap<String,String>();
// map.put("123", TestData.returnParam);
// RedisCache.setMap("test_questionnaire", map);
// for(String b : RedisCache.getMapKeys("test_questionnaire")){
// System.out.print(b+"\t");
// System.out.println(RedisCache.getMapValueByKey("test_questionnaire", b));
// }

// for(String d : RedisCache.getSet("questionnaire_key_list")){
// System.out.println(d);
// }

// RedisCache.setSet("questionnaire_key_list", "hello");
// System.out.println(r.getMapValueByKey("linshi_test", "dati"));

// System.out.println(r.delCacheByKey("drfurl"));
// String keys = "questionnaire_save_123_156_6b078e4c45c24e9786c13651a19bcf46";
// for(String s : r.getMapKeys(keys)){
// System.out.println(s);
// System.out.println(r.getMapValueByKey(keys, s));
// Map<String,Object> a = JSON.parseObject(r.getMapValueByKey(keys, s),Map.class);
// for(Entry<String, Object> mFor : a.entrySet()){
// System.out.println(mFor.getKey()+"\t"+mFor.getValue());
// }
// }
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章