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 shards = new ArrayList();
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 运行异常 redis顶不住了!!!getMaxBorrowWaitTimeMillis:"+
jedisPool.getMaxBorrowWaitTimeMillis()+
"getMeanBorrowWaitTimeMillis:"+jedisPool.getMeanBorrowWaitTimeMillis()+
"getNumActive:"+jedisPool.getNumActive()+
"getNumIdle:"+jedisPool.getNumIdle()+
"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 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 list = getJedis().lrange(key,0,-1);
int count = -1;
for(int i = 0 ;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 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 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 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 getMap(String key){
if(key==null){
return null;
}
return getJedis().hgetAll(key);
}
/**
* 获取所有map的key值
* @param key
* @return
*/
public static Set 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 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 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 jedisList = getJedis().getAllShards();
//
StringBuffer info = new StringBuffer();
//
for(Jedis jedisFor : jedisList){
//
info.append(jedisFor.info());
//
}
//
return info.toString();
}
/**
* 获取所有数据
* @param keyword
* @return
*/
public static Set 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 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 map = new HashMap();
//
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 a = JSON.parseObject(r.getMapValueByKey(keys, s),Map.class);
//
for(Entry mFor : a.entrySet()){
//
System.out.println(mFor.getKey()+"\t"+mFor.getValue());
//
}
//
}
}
}