RedisSingleUtils.java
package com.common.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ch.fm.system.dictionary.entity.DictionaryDetailEntity;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* <p>
* redis工具类
* </p>
* @author why
* @date 2016-7-20上午11:12:28
*/
public class RedisSingleUtils {
public static Logger logger = LoggerFactory.getLogger(RedisSingleUtils.class);
private static JedisPool jedisPool = null;
static {
//从属性文件读取配置
ResourceBundle bundle = ResourceBundle.getBundle("conf.system.system",Locale.CHINESE);
String host = bundle.getString("redis.host");
String port = bundle.getString("redis.port");
int index = StrUtil.isNullOrBlank(bundle.getString("redis.index"))?Integer.valueOf(bundle.getString("redis.index")):0;
String auth = null; //bundle.getString("redis.auth");
try {
JedisPoolConfig config = new JedisPoolConfig();
//config.setMaxTotal(500);
config.setMaxIdle(50);
//config.setMaxWaitMillis(1000);
config.setMaxWait(1000);
config.setTestOnBorrow(true);
// 在还回给pool时,是否提前进行validate操作
config.setTestOnReturn(true);
//连接池设置
jedisPool = new JedisPool(config, host, Integer.parseInt(port), 1800000, auth, index);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
/**
* <p>
* 获得REDIS客户端
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:40:08
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return null;
}
}
/**
* 释放jedis资源
*
* @param jedis
*/
public static void closeJedis(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
//jedis.close();
}
}
/**
* <p>
* 获得KEY所指定的对象。
* </p>
* @author wanghuihui
* @date 2017-7-14下午4:21:14
* @param key
*/
public static Object getObjectByKey(String key){
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
String type = jedis.type(key);
if("string".equalsIgnoreCase(type)){
return jedis.get(key);
}else if("hash".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
//map对应的类型 相当于 redis中的hash
return jedis.hgetAll(key);
}else if("list".equalsIgnoreCase(type)){
Long size = jedis.llen(key);
return jedis.lrange(key, 0, size);
}else if("set".equalsIgnoreCase(type)){
return jedis.smembers(key);
}else if("zset".equalsIgnoreCase(type)){
//有序结果集和无序结果集是一样的,都是SET
//Long size = jedis.zrank(key, member)(key);
return jedis.zrange(key, 0, 10);
}else{
return null;
}
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return null;
}
/**
* <p>
* 获得KEY所指定的对象。
* </p>
* @author wanghuihui
* @date 2017-7-20下午3:09:13
* @param key 键
* @param value 值
* @param isCover 如果已经存在KEY:是否覆盖
* @return
*/
public static Object setObjectByKey(String key,Object value,boolean isCover){
if(null == key || "".equals(key) || key.isEmpty()){
logger.info("key不能空!");
return false;
}
if(null == value || "".equals(value)){
logger.info("value不能空!");
return false;
}
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
boolean isExists = jedis.exists(key);
if(isExists && isCover){
jedis.del(key);
}
String type = jedis.type(key);
if(value instanceof String){//字符串处理
if(isExists && !isCover && !"string".equals(type)){
throw new RuntimeException("类型不匹配!不能添加");
}else{
jedis.set(key, value.toString());
return true;
}
}else if(value instanceof List){//LIST处理
if(isExists && !isCover && !"list".equals(type)){
throw new RuntimeException("类型不匹配!不能添加");
}else{
List<Object> list = (List)value;
if(null == list || list.size()==0){
throw new RuntimeException("对象集合为空!");
}
for(Object obj:list){
String temp = JsonUtil.getJSONString(obj);
jedis.lpush(key,temp);
}
return true;
}
}else if(value instanceof Map){//MAP处理
if(isExists && !isCover && !"hash".equals(type)){
throw new RuntimeException("类型不匹配!不能添加");
}
Map map = (Map)value;
if(null == map || map.size()==0){
throw new RuntimeException("对象集合为空!");
}
jedis.hmset(key, map);
return true;
}else if(value instanceof Set){//set处理
if(isExists && !isCover && !"set".equals(type)){
throw new RuntimeException("类型不匹配!不能添加");
}
Set set = (Set)value;
if(null == set || set.size()==0){
throw new RuntimeException("对象集合为空!");
}
Iterator iterator = set.iterator();
if(iterator.hasNext()){
Object obj = iterator.next();
jedis.sadd(key, JsonUtil.getJSONString(obj));
}
return true;
}else{
jedis.set(key, JsonUtil.getJSONString(value));
return true;
}
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return null;
}
/**
* <p>
* 获得KEY所指定的对象。
* </p>
* @author wanghuihui
* @date 2017-7-20下午3:09:13
* @param key 键
* @param value 值
* @param isCover 如果已经存在KEY:是否覆盖
* @return
*/
public static Object setObjectToStrByKey(String key,Object value,boolean isCover){
if(null == key || "".equals(key) || key.isEmpty()){
logger.info("key不能空!");
return false;
}
if(null == value || "".equals(value)){
logger.info("value不能空!");
return false;
}
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
boolean isExists = jedis.exists(key);
if(isExists && isCover){
jedis.del(key);
}
jedis.set(key, JsonUtil.getJSONString(value));
return true;
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return null;
}
/**
* <p>
* str put
* </p>
* @author wanghuihui
* @date 2017-7-14下午2:43:58
* @param key
* @param value
*/
public static void strPut(String key, String value) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.set(key, value);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 获得KEY对应的字符串
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:40:50
* @param key
* @return
*/
public static String strGet(String key) {
String value = "";
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
value = jedis.get(key);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return value;
}
/**
* <p>
* 删除KEY对应的字符串
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:40:50
* @param key
* @return
*/
public static Long strDel(String... key) {
Long value = 0L;
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
value = jedis.del(key);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return value;
}
/**
* <p>
* 发布订阅
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:41:38
* @param theme
* @param message
*/
public static void publish(String theme, String message) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.publish(theme, message);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 设置过期时间
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:41:54
* @param key
* @param seconds
*/
public static void keyExpire(String key, int seconds) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.expire(key, seconds);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 判断是否存在
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:42:10
* @param key
* @return
*/
public static boolean keyExists(String key) {
boolean bool = false;
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
bool = jedis.exists(key);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return bool;
}
/**
* <p>
* key对应的VALUE增加 integer.
* </p>
* @author wanghuihui
* @date 2017-7-20下午1:42:26
* @param key
* @param integer
*/
public static void valueIncr(String key,long integer) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.incrBy(key,integer);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* set集合增加。
* </p>
* @author wanghuihui
* @date 2017-7-14下午2:13:39
* @param key
* @param members
*/
public static void setAdd(String key, String... members) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.sadd(key, members);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
//jedisPool.destroy();
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 如果成员是存储在键中的集合的成员,则返回1,否则返回0。
* </p>
* @author wanghuihui
* @date 2017-7-14下午2:04:54
* @param key
* @param members
* @return
*/
public static boolean setExists(String key, String members) {
Jedis jedis = null;
boolean bool = false;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
bool = jedis.sismember(key, members);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
return bool;
}
/**
* <p>
* 有序集合
* </p>
* @author wanghuihui
* @date 2017-7-14下午3:05:13
* @param key:键
* @param score:排序依据,SCORE越小越前。
* @param members :成员
*/
public static void zSetAdd(String key, double score , String member) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.zadd(key, score,member);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 有序集合查询:相当于排序分页查询。
* </p>
* @author wanghuihui
* @date 2017-7-14下午3:24:58
* @param key:
* @param start 开始
* @param limit 结束
*/
public static void zSetQuery(String key, int start , int limit) {
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.zrange(key, start,limit);
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
/**
* <p>
* 清空当前数据库
* </p>
* @author wanghuihui
* @date 2017-7-14下午4:04:08
*/
public static void flushDBAll(){
Jedis jedis = null;
// 从池中获取一个jedis实例
try {
jedis = getJedis();
jedis.flushDB();
} catch (Exception e) {
// 销毁对象
jedisPool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
// 还回到连接池
closeJedis(jedis);
}
}
public static void main(String[] args) {
RedisSingleUtils jedisUtil = new RedisSingleUtils();
//jedisUtil.testAll();
//jedisUtil.testSet();
List<DictionaryDetailEntity> list = (List<DictionaryDetailEntity>) RedisSingleUtils.getObjectByKey("list_dic_detail");
System.out.println(11);
JsonUtil.getObjectArrayFromJson(list.toString());
System.out.println(list.size());
for(DictionaryDetailEntity dic : list){
System.out.println(dic.getLabel());
}
}
/**
* <p>
* 測試
* </p>
* @author wanghuihui
* @date 2017-7-14下午2:33:49
*/
private void testAll(){
Jedis jedis = RedisSingleUtils.getJedis();
// 设置字符串数据
jedis.set("runoobkey", "Redis");
jedis.set("str_01", "10");
this.valueIncr("str_01",1);
System.out.println(this.strGet("str_01"));
// 获取存储的数据并输出
System.out.println("Stored string in redis: " + jedis.get("runoobkey"));
/**
* Redis Java Hash(哈希)实例
*/
// 设置哈希数据
Map<String, String> map = new HashMap<String, String>();
map.put("1", "name1");
map.put("2", "name2");
map.put("3", "name3");
jedis.hmset("redisHash", map);
// 获取存储的数据并输出
System.out.println("Stored Hash in redis: " + jedis.hgetAll("redisHash"));
/**
* Redis Java List(列表)实例
*/
// 存储数据到列表中
jedis.lpush("redisList", "1");
jedis.lpush("redisList", "2");
jedis.lpush("redisList", "3");
// 获取存储数据并输出
List<String> redisList = jedis.lrange("redisList", 0, 10);
for (String redis : redisList) {
System.out.println("Stored List in redis: " + redis);
}
/**
* Redis Java Set(集合)实例
*/
// 存储数据到集合中
jedis.sadd("redisSet", "1", "2", "3", "3");
jedis.sadd("redisSet", "22", "43");
//测试程序会覆盖原来的SET。
jedis.set("redisSet", "1");
// 获取存储数据并输出
System.out.println("Stored Set in redis: " + jedis.smembers("redisSet"));
/**
* Redis Java ZSet(有序集合)实例
*/
// 存储数据到有序集合中
jedis.zadd("redisZSet", 10, "3");
jedis.zadd("redisZSet", 20, "4");
jedis.zadd("redisZSet", 5, "2");
jedis.zadd("redisZSet", 3, "1");
String ty = jedis.type("redisZSet");
// 获取存储数据并输出
System.out.println("Stored ZSet in redis: " + jedis.zrange("redisZSet", 0, 10));
/**
* 获取Reids所有的KEY
*/
// 获取数据并输出
Set<String> keys = jedis.keys("*");
Set<String> keys2 = jedis.keys("*nach*");
for (String key : keys) {
System.out.println("Set of stored key: " + key);
String type = jedis.type(key);
Object value = this.getObjectByKey(key);
if(null == value){
System.out.println("类型为空!请检查~");
}else if(value instanceof String){
System.out.println("value="+value);
}else if(value instanceof List){
List list = (List) value;
System.out.println(list.size());
}else if(value instanceof Map){
Map map2 = (Map)value;
System.out.println(11);
}else if(value instanceof Set){
Set set = (Set)value;
System.out.println(11);
}else {
System.out.println(value.getClass());
}
}
this.flushDBAll(); //清空当前数据库
}
private void testSet() {
Jedis jedis = RedisSingleUtils.getJedis();
/**
* SET 集合
*/
setAdd("spinach", "mem1", "mem2", "mem3", "mem4");
Boolean isExist = setExists("spinach","mem2");
zSetAdd("spinachZet", 20, "mem20");
zSetAdd("spinachZet", 2, "mem2");
zSetAdd("spinachZet", 01, "mem01");
zSetAdd("spinachZet", 5, "mem5");
zSetAdd("spinachZet", 2, "mem02");
zSetAdd("spinachZet", 6, "mem6");
zSetAdd("spinachZet", 3, "mem3");
zSetAdd("spinachZet", 14, "mem14");
zSetAdd("spinachZet", 10, "mem10");
Set<String> result = jedis.zrange("spinachZet", 0, 5);
System.out.println(result);
Boolean isExist2 = jedis.sismember("spinachZet","mem14");
System.out.println(jedis.exists("spinachZet"));
/*
Long start = System.currentTimeMillis();
for(int i=0;i<100000;i++){
jedis.set("key"+i,"value # Warning: since Redis is pretty fast an outside user can try up to aaaaaaaa"+i);
}
Long end = System.currentTimeMillis();
for(int i=0;i<100000;i++){
put("key"+i,"value # Warning: since Redis is pretty fast an outside user can try up to aaaaaaaa"+i);
}
Long end2 =System.currentTimeMillis();
Long t1 = end - start;
Long t2 = end2 -end;
System.out.println("t1="+t1+" t2="+t2); //t1=5942 t2=17037
*/
}
}