- 浏览: 51445 次
- 性别:
- 来自: 深圳
文章分类
- 全部博客 (111)
- Java编程语言 (11)
- Tomcat中间件 (4)
- Linux操作系统 (3)
- Http协议 (3)
- Java虚拟机 (9)
- 计算机网络 (1)
- Mysql数据库 (8)
- Web前端 (5)
- 数据库基础 (3)
- 软件架构 (1)
- 面试题 (1)
- Oracle数据库 (5)
- ES中间件 (4)
- 问题定位及性能优化 (6)
- 性能测试 (0)
- Spring框架 (12)
- 大数据计算 (1)
- 数据结构与算法 (2)
- Redis中间件 (6)
- 数据持久化框架 (1)
- Memcache缓存 (3)
- Nginx组件 (1)
- 项目实战 (0)
- 安全优化 (0)
- 安全优化与限流防刷 (1)
- Zookeeper組件 (3)
- docker组件 (2)
- solr组件 (2)
- 分布式架构 (1)
- 正则表达式 (1)
- vue (1)
- 其它 (0)
- 工具配置 (1)
- K8S (1)
最新评论
Redis帮助类
redis.properties
配置文件内容
redis.pool.maxActive=100
redis.pool.maxIdle=20
redis.pool.maxWait=3000
redis.pool.testOnBorrow=false
redis.pool.testOnReturn=false
redis.ip=127.0.0.1
redis.port=6379
redis.port1=6380
redis.password=****
package com.szreach.rcrp.redis;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.log4j.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class RedisUtil {
private static final Logger log = Logger.getLogger(RedisUtil.class);
private static JedisPool jedisPool = null;
private static ShardedJedisPool shardedJedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
// 加载redis配置文件
ResourceBundle bundle = ResourceBundle.getBundle("redis");
if (bundle == null) {
throw new IllegalArgumentException(
"[redis.properties] is not found!");
}
int maxActivity = Integer.valueOf(bundle
.getString("redis.pool.maxActive"));
int maxIdle = Integer.valueOf(bundle
.getString("redis.pool.maxIdle"));
long maxWait = Long.valueOf(bundle.getString("redis.pool.maxWait"));
boolean testOnBorrow = Boolean.valueOf(bundle
.getString("redis.pool.testOnBorrow"));
boolean onreturn = Boolean.valueOf(bundle
.getString("redis.pool.testOnReturn"));
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
config.setMaxActive(maxActivity);
config.setMaxIdle(maxIdle); //最大空闲连接数
config.setMaxWait(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(onreturn);
jedisPool = new JedisPool(config, bundle.getString("redis.ip"),
Integer.valueOf(bundle.getString("redis.port")), 10000,
bundle.getString("redis.password"));
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(bundle.getString("redis.ip"), Integer
.valueOf(bundle.getString("redis.port1"))));
shardedJedisPool = new ShardedJedisPool(config, shards);
log.info("初始化Redis连接池success");
} catch (Exception e) {
log.error("初始化Redis连接池 出错!", e);
}
}
/**
* 获取Jedis实例
*
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
log.error("Redis缓存获取Jedis实例 出错!", e);
return null;
}
}
/**
* 获取shardedJedis实例
*
* @return
*/
public static ShardedJedis getShardedJedis() {
try {
if (shardedJedisPool != null) {
ShardedJedis resource = shardedJedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
log.error("Redis缓存获取shardedJedis实例 出错!", e);
return null;
}
}
/**
* 释放jedis资源
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 释放shardedJedis资源
*
* @param jedis
*/
public static void returnResource(final ShardedJedis shardedJedis) {
if (shardedJedis != null) {
shardedJedisPool.returnResource(shardedJedis);
}
}
/**
* 向缓存中设置字符串内容
*
* @param key
* key
* @param value
* value
* @return
* @throws Exception
*/
public static boolean set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
if(jedis != null){
jedis.set(key, value);
}
return true;
} catch (Exception e) {
log.error("Redis缓存设置key值 出错!", e);
return false;
} finally {
returnResource(jedis);
}
}
/**
* 判断key是否存在
*/
public static boolean exists(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis == null) {
return false;
} else {
return jedis.exists(key);
}
} catch (Exception e) {
log.error("Redis缓存判断key是否存在 出错!", e);
return false;
} finally {
returnResource(jedis);
}
}
/**
* 删除缓存中的对象,根据key
* @param key
* @return
*/
public static boolean del(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//*******************key-value****************start
/**
* 向缓存中设置对象
*
* @param key
* @param value
* @return
*/
public static boolean set(String key, Object value) {
Jedis jedis = null;
try {
String objectJson = JSONObject.fromObject(value).toString();
jedis = getJedis();
if (jedis != null) {
jedis.set(key, objectJson);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 根据key 获取内容
*
* @param key
* @return
*/
public static Object get(String key) {
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
Object value = jedis.get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
shardedJedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key, Class<T> clazz) {
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
return (T) JSONObject.toBean(JSONObject.fromObject(jedis.get(key)), clazz);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//*******************key-value****************end
//*************** 操作list****************start
/**
* 向缓存中设置对象
* @param key
* @param list
* T string calss
* @return
*/
public static <T> boolean setList(String key,List<T> list){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
for (T vz : list) {
if (vz instanceof String) {
jedis.lpush(key, (String) vz);
} else {
String objectJson = JSONObject.fromObject(vz).toString();
jedis.lpush(key, objectJson);
}
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getListEntity(String key,Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
List<String> valueJson = jedis.lrange(key, 0, -1);
JSONArray json = new JSONArray();
json.addAll(valueJson);
JSONArray jsonArray = JSONArray.fromObject(json.toString());
return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static List<String> getListString(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
return jedis.lrange(key, 0, -1);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//*************** 操作list****************end
//*************** 操作map****************start
public static <K,V> boolean setMap(String key,Map<String,V> map){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
if (kv.getValue() instanceof String) {
jedis.hset(key, kv.getKey(), (String) kv.getValue());
}else if (kv.getValue() instanceof List) {
jedis.hset(key, kv.getKey(), JSONArray.fromObject(kv.getValue()).toString());
} else {
jedis.hset(key, kv.getKey(), JSONObject.fromObject(kv.getValue()).toString());
}
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
public static boolean setMapKey(String key,String mapKey,Object value){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
if (value instanceof String) {
jedis.hset(key, mapKey, String.valueOf(value));
} else if (value instanceof List) {
jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
} else {
jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* seconds key和value 保存的有效时间(单位:秒)
* @return
*/
public static boolean setMapKeyExpire(String key,String mapKey,Object value, int seconds){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
if (value instanceof String) {
jedis.hset(key, mapKey, String.valueOf(value));
} else if (value instanceof List) {
jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
} else {
jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
}
jedis.expire(key, seconds);
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,V> getMap(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
return map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,V> getMapEntityClass(String key,Class<V> clazz){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
map.put(kv.getKey(), (V) JSONObject.toBean(JSONObject.fromObject(kv.getValue()), clazz));
}
return map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,List<V>> getMapList(String key,Class<V> clazz){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
JSONArray jsonArray = JSONArray.fromObject(kv.getValue());
map.put(kv.getKey(), (V) JSONArray.toCollection(jsonArray, clazz));
}
return (Map<String, List<V>>) map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getMapKeyListEntity(String key,String mapKey,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
String valueJson = jedis.hget(key, mapKey);
JSONArray jsonArray = JSONArray.fromObject(valueJson);
return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> T getMapKeyEntity(String key,String mapKey,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if(jedis != null){
String valueJson=jedis.hget(key, mapKey);
return (T) JSONObject.toBean(JSONObject.fromObject(valueJson), entityClass);
}else{return null;}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static Object getMapKey(String key,String mapKey){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if(jedis != null){
return jedis.hget(key, mapKey);
}else{return null;}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static boolean delMapKey(String key,String mapKey){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hdel(key, mapKey);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
public static boolean hexists(String key,String mapKey){
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.hexists(key,mapKey);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
shardedJedisPool.returnResource(jedis);
}
}
//*************** 操作map****************end
//***************计数器应用INCR,DECR****************begin
//Redis的命令都是原子性的,你可以轻松地利用INCR,DECR命令来构建计数器系统
/**
* incr(key):名称为key的string增1操作
*/
public static boolean incr(String key){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.incr(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* incrby(key, integer):名称为key的string增加integer
*/
public static boolean incrBy(String key, int value){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.incrBy(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* decr(key):名称为key的string减1操作
*/
public static boolean decr(String key){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.decr(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* decrby(key, integer):名称为key的string减少integer
*/
public static boolean decrBy(String key, int value){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.decrBy(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//***************计数器应用INCR,DECR****************end
//***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************begin
/**
* 向名称为key的zset中添加元素member,score用于排序。
* 如果该元素已经存在,则根据score更新该元素的顺序
*/
public static boolean zadd(String key, double score, String member){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.zadd(key, score, member);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 删除名称为key的zset中的元素member
*/
public static boolean zrem(String key, String... members){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.zrem(key, members);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 返回集合中score在给定区间的元素
*/
public static Set<String> zrangeByScore(String key, double min, double max){
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.zrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************end
//***************sorted set 处理***************************************begin
//zset 处理
public static boolean zaddObject(String key, double score, Object value){
Jedis jedis = null;
try {
jedis = getJedis();
String objectJson = JSONObject.fromObject(value).toString();
jedis.zadd(key, score, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* score值递减(从大到小)次序排列。
* @param key
* @param max score
* @param min score
* @param entityClass
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> zrevrangeByScore(String key,double max,double min,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
Set<String> set=jedis.zrevrangeByScore(key, max, min);
List<T> list=new ArrayList<T>();
for (String str : set) {
list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
/**
* score值递减(从大到小)次序排列。
* @param key
* @param max score
* @param min score
* @param offset count (类似mysql的 LIMIT)
* @param entityClass
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> zrevrangeByScore(String key,double max,double min,
int offset, int count,Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
Set<String> set=jedis.zrevrangeByScore(key, max, min,offset,count);
List<T> list=new ArrayList<T>();
for (String str : set) {
list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//得到总记录数
public static long zcard(String key){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
return jedis.zcard(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//删除 元素
public static boolean zremObject(String key, Object value){
Jedis jedis = null;
try {
jedis = getJedis();
String objectJson = JSONObject.fromObject(value).toString();
jedis.zrem(key, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//统计zset集合中score某个范围内(1-5),元素的个数
public static long zcount(String key,double min, double max){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
return jedis.zcount(key,min,max);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//查看zset集合中元素的score
public static double zscore(String key,Object value){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
String objectJson = JSONObject.fromObject(value).toString();
return jedis.zscore(key,objectJson);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//**************sorted set******************************************end
//***********************Redis Set集合操作**************************begin
/**
* sadd:向名称为Key的set中添加元素,同一集合中不能出现相同的元素值。(用法:sadd set集合名称 元素值)
* @param key
* @param value
* @return
*/
public static boolean sadd(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.sadd(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* srem:删除名称为key的set中的元素。(用法:srem set集合名称 要删除的元素值)
*
* @param key
* @param value
* @return
*/
public static boolean srem(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.srem(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* sdiff:返回所有给定key与第一个key的差集。(用法:sdiff set集合1 set集合2)
*
* @param key1
* @param key2
* @return
*/
public static Set<String> sdiff(String key1, String key2) {
Jedis jedis = null;
Set<String> diffList = null;
try {
jedis = getJedis();
diffList = jedis.sdiff(key1, key2);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return diffList;
}
/**
* sismember:判断某个值是否是集合的元素。(用法:sismember 集合1 指定的元素值)
*
* @param key
* @param value
* @return
*/
public static boolean sismember(String key, String value) {
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.sismember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* smembers(key) :返回名称为key的set的所有元素
*
* @param key
* @return
*/
public static Set<String> smembers(String key) {
Jedis jedis = null;
Set<String> list = null;
try {
jedis = getJedis();
list = jedis.smembers(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return list;
}
//***********************Redis Set集合操作****************************end
}
配置文件内容
redis.pool.maxActive=100
redis.pool.maxIdle=20
redis.pool.maxWait=3000
redis.pool.testOnBorrow=false
redis.pool.testOnReturn=false
redis.ip=127.0.0.1
redis.port=6379
redis.port1=6380
redis.password=****
package com.szreach.rcrp.redis;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.log4j.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class RedisUtil {
private static final Logger log = Logger.getLogger(RedisUtil.class);
private static JedisPool jedisPool = null;
private static ShardedJedisPool shardedJedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
// 加载redis配置文件
ResourceBundle bundle = ResourceBundle.getBundle("redis");
if (bundle == null) {
throw new IllegalArgumentException(
"[redis.properties] is not found!");
}
int maxActivity = Integer.valueOf(bundle
.getString("redis.pool.maxActive"));
int maxIdle = Integer.valueOf(bundle
.getString("redis.pool.maxIdle"));
long maxWait = Long.valueOf(bundle.getString("redis.pool.maxWait"));
boolean testOnBorrow = Boolean.valueOf(bundle
.getString("redis.pool.testOnBorrow"));
boolean onreturn = Boolean.valueOf(bundle
.getString("redis.pool.testOnReturn"));
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
config.setMaxActive(maxActivity);
config.setMaxIdle(maxIdle); //最大空闲连接数
config.setMaxWait(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(onreturn);
jedisPool = new JedisPool(config, bundle.getString("redis.ip"),
Integer.valueOf(bundle.getString("redis.port")), 10000,
bundle.getString("redis.password"));
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(bundle.getString("redis.ip"), Integer
.valueOf(bundle.getString("redis.port1"))));
shardedJedisPool = new ShardedJedisPool(config, shards);
log.info("初始化Redis连接池success");
} catch (Exception e) {
log.error("初始化Redis连接池 出错!", e);
}
}
/**
* 获取Jedis实例
*
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
log.error("Redis缓存获取Jedis实例 出错!", e);
return null;
}
}
/**
* 获取shardedJedis实例
*
* @return
*/
public static ShardedJedis getShardedJedis() {
try {
if (shardedJedisPool != null) {
ShardedJedis resource = shardedJedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
log.error("Redis缓存获取shardedJedis实例 出错!", e);
return null;
}
}
/**
* 释放jedis资源
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 释放shardedJedis资源
*
* @param jedis
*/
public static void returnResource(final ShardedJedis shardedJedis) {
if (shardedJedis != null) {
shardedJedisPool.returnResource(shardedJedis);
}
}
/**
* 向缓存中设置字符串内容
*
* @param key
* key
* @param value
* value
* @return
* @throws Exception
*/
public static boolean set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
if(jedis != null){
jedis.set(key, value);
}
return true;
} catch (Exception e) {
log.error("Redis缓存设置key值 出错!", e);
return false;
} finally {
returnResource(jedis);
}
}
/**
* 判断key是否存在
*/
public static boolean exists(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis == null) {
return false;
} else {
return jedis.exists(key);
}
} catch (Exception e) {
log.error("Redis缓存判断key是否存在 出错!", e);
return false;
} finally {
returnResource(jedis);
}
}
/**
* 删除缓存中的对象,根据key
* @param key
* @return
*/
public static boolean del(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//*******************key-value****************start
/**
* 向缓存中设置对象
*
* @param key
* @param value
* @return
*/
public static boolean set(String key, Object value) {
Jedis jedis = null;
try {
String objectJson = JSONObject.fromObject(value).toString();
jedis = getJedis();
if (jedis != null) {
jedis.set(key, objectJson);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 根据key 获取内容
*
* @param key
* @return
*/
public static Object get(String key) {
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
Object value = jedis.get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
shardedJedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key, Class<T> clazz) {
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
return (T) JSONObject.toBean(JSONObject.fromObject(jedis.get(key)), clazz);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//*******************key-value****************end
//*************** 操作list****************start
/**
* 向缓存中设置对象
* @param key
* @param list
* T string calss
* @return
*/
public static <T> boolean setList(String key,List<T> list){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
for (T vz : list) {
if (vz instanceof String) {
jedis.lpush(key, (String) vz);
} else {
String objectJson = JSONObject.fromObject(vz).toString();
jedis.lpush(key, objectJson);
}
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getListEntity(String key,Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
List<String> valueJson = jedis.lrange(key, 0, -1);
JSONArray json = new JSONArray();
json.addAll(valueJson);
JSONArray jsonArray = JSONArray.fromObject(json.toString());
return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static List<String> getListString(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
return jedis.lrange(key, 0, -1);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//*************** 操作list****************end
//*************** 操作map****************start
public static <K,V> boolean setMap(String key,Map<String,V> map){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
if (kv.getValue() instanceof String) {
jedis.hset(key, kv.getKey(), (String) kv.getValue());
}else if (kv.getValue() instanceof List) {
jedis.hset(key, kv.getKey(), JSONArray.fromObject(kv.getValue()).toString());
} else {
jedis.hset(key, kv.getKey(), JSONObject.fromObject(kv.getValue()).toString());
}
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
public static boolean setMapKey(String key,String mapKey,Object value){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
if (value instanceof String) {
jedis.hset(key, mapKey, String.valueOf(value));
} else if (value instanceof List) {
jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
} else {
jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
}
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* seconds key和value 保存的有效时间(单位:秒)
* @return
*/
public static boolean setMapKeyExpire(String key,String mapKey,Object value, int seconds){
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis != null) {
if (value instanceof String) {
jedis.hset(key, mapKey, String.valueOf(value));
} else if (value instanceof List) {
jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
} else {
jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
}
jedis.expire(key, seconds);
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,V> getMap(String key){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
return map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,V> getMapEntityClass(String key,Class<V> clazz){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
map.put(kv.getKey(), (V) JSONObject.toBean(JSONObject.fromObject(kv.getValue()), clazz));
}
return map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <K,V> Map<String,List<V>> getMapList(String key,Class<V> clazz){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
Set<Map.Entry<String, V>> entry = map.entrySet();
for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
Map.Entry<String, V> kv = ite.next();
JSONArray jsonArray = JSONArray.fromObject(kv.getValue());
map.put(kv.getKey(), (V) JSONArray.toCollection(jsonArray, clazz));
}
return (Map<String, List<V>>) map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getMapKeyListEntity(String key,String mapKey,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if (jedis != null) {
String valueJson = jedis.hget(key, mapKey);
JSONArray jsonArray = JSONArray.fromObject(valueJson);
return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> T getMapKeyEntity(String key,String mapKey,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if(jedis != null){
String valueJson=jedis.hget(key, mapKey);
return (T) JSONObject.toBean(JSONObject.fromObject(valueJson), entityClass);
}else{return null;}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static Object getMapKey(String key,String mapKey){
ShardedJedis jedis = null;
try {
jedis = getShardedJedis();
if(jedis != null){
return jedis.hget(key, mapKey);
}else{return null;}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
public static boolean delMapKey(String key,String mapKey){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hdel(key, mapKey);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
public static boolean hexists(String key,String mapKey){
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.hexists(key,mapKey);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
shardedJedisPool.returnResource(jedis);
}
}
//*************** 操作map****************end
//***************计数器应用INCR,DECR****************begin
//Redis的命令都是原子性的,你可以轻松地利用INCR,DECR命令来构建计数器系统
/**
* incr(key):名称为key的string增1操作
*/
public static boolean incr(String key){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.incr(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* incrby(key, integer):名称为key的string增加integer
*/
public static boolean incrBy(String key, int value){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.incrBy(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* decr(key):名称为key的string减1操作
*/
public static boolean decr(String key){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.decr(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* decrby(key, integer):名称为key的string减少integer
*/
public static boolean decrBy(String key, int value){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.decrBy(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//***************计数器应用INCR,DECR****************end
//***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************begin
/**
* 向名称为key的zset中添加元素member,score用于排序。
* 如果该元素已经存在,则根据score更新该元素的顺序
*/
public static boolean zadd(String key, double score, String member){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.zadd(key, score, member);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 删除名称为key的zset中的元素member
*/
public static boolean zrem(String key, String... members){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.zrem(key, members);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* 返回集合中score在给定区间的元素
*/
public static Set<String> zrangeByScore(String key, double min, double max){
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.zrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************end
//***************sorted set 处理***************************************begin
//zset 处理
public static boolean zaddObject(String key, double score, Object value){
Jedis jedis = null;
try {
jedis = getJedis();
String objectJson = JSONObject.fromObject(value).toString();
jedis.zadd(key, score, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* score值递减(从大到小)次序排列。
* @param key
* @param max score
* @param min score
* @param entityClass
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> zrevrangeByScore(String key,double max,double min,
Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
Set<String> set=jedis.zrevrangeByScore(key, max, min);
List<T> list=new ArrayList<T>();
for (String str : set) {
list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
/**
* score值递减(从大到小)次序排列。
* @param key
* @param max score
* @param min score
* @param offset count (类似mysql的 LIMIT)
* @param entityClass
* @return
*/
@SuppressWarnings("unchecked")
public static <T> List<T> zrevrangeByScore(String key,double max,double min,
int offset, int count,Class<T> entityClass){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
Set<String> set=jedis.zrevrangeByScore(key, max, min,offset,count);
List<T> list=new ArrayList<T>();
for (String str : set) {
list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
returnResource(jedis);
}
}
//得到总记录数
public static long zcard(String key){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
return jedis.zcard(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//删除 元素
public static boolean zremObject(String key, Object value){
Jedis jedis = null;
try {
jedis = getJedis();
String objectJson = JSONObject.fromObject(value).toString();
jedis.zrem(key, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
//统计zset集合中score某个范围内(1-5),元素的个数
public static long zcount(String key,double min, double max){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
return jedis.zcount(key,min,max);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//查看zset集合中元素的score
public static double zscore(String key,Object value){
ShardedJedis jedis = null;
try {
jedis =shardedJedisPool.getResource();
String objectJson = JSONObject.fromObject(value).toString();
return jedis.zscore(key,objectJson);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
returnResource(jedis);
}
}
//**************sorted set******************************************end
//***********************Redis Set集合操作**************************begin
/**
* sadd:向名称为Key的set中添加元素,同一集合中不能出现相同的元素值。(用法:sadd set集合名称 元素值)
* @param key
* @param value
* @return
*/
public static boolean sadd(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.sadd(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* srem:删除名称为key的set中的元素。(用法:srem set集合名称 要删除的元素值)
*
* @param key
* @param value
* @return
*/
public static boolean srem(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.srem(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* sdiff:返回所有给定key与第一个key的差集。(用法:sdiff set集合1 set集合2)
*
* @param key1
* @param key2
* @return
*/
public static Set<String> sdiff(String key1, String key2) {
Jedis jedis = null;
Set<String> diffList = null;
try {
jedis = getJedis();
diffList = jedis.sdiff(key1, key2);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return diffList;
}
/**
* sismember:判断某个值是否是集合的元素。(用法:sismember 集合1 指定的元素值)
*
* @param key
* @param value
* @return
*/
public static boolean sismember(String key, String value) {
ShardedJedis jedis = null;
try {
jedis = shardedJedisPool.getResource();
return jedis.sismember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
returnResource(jedis);
}
}
/**
* smembers(key) :返回名称为key的set的所有元素
*
* @param key
* @return
*/
public static Set<String> smembers(String key) {
Jedis jedis = null;
Set<String> list = null;
try {
jedis = getJedis();
list = jedis.smembers(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return list;
}
//***********************Redis Set集合操作****************************end
}
相关推荐
"Asp.net 封装Redis帮助类"的主题涉及了如何在Asp.net应用程序中有效地利用Redis进行数据缓存。下面我们将详细探讨这个主题。 首先,`StackExchange.Redis.dll`是.NET平台上的一个流行的Redis客户端库,它提供了一...
C# Redis帮助类,用户Redis配置及使用的帮助类文件,web.config需要配置
一个小demo,利用单例模式通过接口和redis帮助类连接redis,并获取redis中库中的数据,以及将数据写入到redis库中,项目为vs2017创建
这个“Redis帮助类DLL源码”提供了一种便捷的方式,帮助开发者更高效地与Redis服务器进行交互。 首先,让我们深入了解一下Redis的基础知识。Redis是一个开源的、基于内存的数据结构存储系统,它可以当作数据库、...
StackExchange.Redis的帮助类
描述中提到的"redis帮助类"是指为方便.NET开发者使用Redis而编写的C#类库。这个类库通常包含了一系列的方法和属性,用于执行如设置、获取、删除键值对,以及对集合类型(如set、list、有序set)进行操作。Set是无序...
StackExchange.redis 封装帮助类(支持批量)
org.springframework.data.redis.core.StringRedisTemplate,spring boot集成redis后操作类,封装后完全是针对redis命令调用
* servicestack.redis为github中的开源项目 * redis是一个典型的k/v型数据库 * redis共支持五种类型的数据 string,list,hash,set,sortedset * * string是最简单的字符串类型 * * list是字符串列表,其内部是...
"php-redis中文帮助手册.zip"提供了一份详尽的中文指南,旨在帮助开发者充分利用PHP与Redis的集成优势。 1. PHP扩展安装与配置: 在PHP中使用Redis,首先需要安装PHP的Redis扩展。这个过程通常涉及下载源码,编译...
Redis 是一个开源的,基于键值对的数据存储系统,常被用作数据库、缓存和消息中间件。它以其高性能、高可用性以及丰富的数据结构而著名。在Unity游戏开发中,Redis 可能用于存储游戏状态、玩家数据或者实现多玩家...
文章是redisUtils工具类的封装,和基于springboot环境的单元测试; 文中封装了redis的众多方法,希望对您有所帮助。
本知识点将详细讨论如何在C++中封装Redis访问类,以及实现set和get操作。 首先,为了在C++中与Redis进行交互,我们需要一个客户端库。一个常用的C++ Redis客户端库是`rediscpp`或`hiredis`。这两个库提供了C++接口...
本资料包提供了关于Java操作Redis的代码示例和工具类,旨在帮助开发者更好地理解和应用Java与Redis的集成。 首先,让我们深入了解一下Redis。Redis是一个开源的内存数据结构存储系统,支持数据类型如字符串、哈希、...
开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理...
这个"php的Redis类操作.zip"压缩包提供了一个PHP类,可以帮助开发者与Redis服务器进行交互。下面我们将深入探讨这个PHP Redis类的关键知识点,以及如何使用它。 1. **Redis类初始化**: 在PHP中,连接到Redis...
### .NET 下 Redis 操作类的关键知识点 #### 一、概述 在.NET环境中,使用Redis作为数据存储或缓存服务非常普遍。为了更好地利用Redis的功能并优化其性能,开发人员通常会封装一个自定义的Redis操作类。此类可以...
这个“Redis工具类”就是为了简化Redis的读写操作而设计的,它能够帮助开发者更高效、更便捷地在应用程序中集成Redis功能。 Redis工具类通常包含以下关键功能: 1. **连接管理**:初始化和关闭与Redis服务器的连接...
本篇文章将详细解析`redis工具类`的设计和实现,以及它如何帮助开发者更高效地操作Redis。 首先,`redis工具类`的核心功能在于创建和管理Jedis实例。Jedis对象是与Redis服务器通信的桥梁,但为了防止资源泄露,我们...