RedisUtil.java
package com.x.voiceandtextreceiver.component;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.setting.Setting;
import x.voiceandtextreceiver.utils.MyBase64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple;
import java.util.*;
@Component
public class RedisUtil {
private String ADDR_ARRAY = "";
// Redis的端口号
private int PORT = 1;
// 访问密码
private String AUTH = "";
// 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private int MAX_ACTIVE = 1;
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private int MAX_IDLE = 1;
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private int MAX_WAIT = 1;
// 超时时间
private int TIMEOUT = 1;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private boolean TEST_ON_BORROW = true;
private RedisDS redisds = null;
// private JedisPool jedisPool = null;
/**
* redis过期时间,以秒为单位
*/
public final int EXRP_HOUR = 60 * 60; // 一小时
public final int EXRP_DAY = 60 * 60 * 24; // 一天
public final int EXRP_MONTH = 60 * 60 * 24 * 30; // 一个月
public final int INDEX_DB = 2;
@Value("${spring.redis.password}")
private String passwords;
@Value("${spring.redis.host}")
private String url;
@Value("${spring.redis.port}")
private String port;
/**
* 在多线程环境同步初始化
*/
private synchronized void poolInit() {
try {
if (redisds == null) {
Setting setting = new Setting("redis.properties");
String password = new String(MyBase64.getUrlDecoder().decode(passwords));
setting.set("password", password);
setting.set("host", url);
setting.set("port", port);
AUTH = password;
redisds = RedisDS.create(setting, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 同步获取Jedis实例
*
* @return Jedis
*/
public synchronized Jedis getJedis() {
Jedis jedis = null;
try {
poolInit();
jedis = redisds.getJedis();
if (jedis != null) {
jedis.auth(AUTH);
}
} catch (Exception e) {
// // BaseLog.error("Redis Connection Error");
e.printStackTrace();
}
return jedis;
}
/**
* 同步获取Jedis实例
*
* @return Jedis
*/
// public synchronized Jedis getJedis() {
// Jedis jedis = null;
// try {
// poolInit();
// jedis=redisds.getJedis();
// if(jedis!=null && !StringEx.isEmpty(AUTH)){
// jedis.auth(AUTH);
// }
// } catch (Exception e) {
// // BaseLog.error("Get jedis error : "+e);
// }
// return jedis;
// }
/**
* 释放jedis资源
*
* @param jedis
*/
public void returnResource(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* 设置 String
*
* @param key
* @param value
*/
public boolean setString(String key, String value, int indexDb) {
boolean result = false;
Jedis jedis = null;
try {
value = StringUtils.isEmpty(value) ? "" : value;
jedis = getJedis();
if (jedis == null) {
return false;
}
jedis.select(indexDb);
jedis.set(key, value);
result = true;
} catch (Exception e) {
// // BaseLog.error("Redis setString Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置 过期时间
*
* @param key
* @param seconds 以秒为单位
* @param value
*/
public boolean setString(String key, int seconds, String value, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
try {
value = StringUtils.isEmpty(value) ? "" : value;
jedis.select(indexDb);
jedis.setex(key, seconds, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public boolean zadd(String key, int seconds, String value, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
try {
value = StringUtils.isEmpty(value) ? "" : value;
jedis.select(indexDb);
jedis.zadd(key, seconds, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public long zrem(String key, String value, int indexDb) {
long result = 0;
Jedis jedis = getJedis();
if (jedis == null) {
return result;
}
try {
value = StringUtils.isEmpty(value) ? "" : value;
jedis.select(indexDb);
result = jedis.zrem(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public Set<Tuple> zrangeWithScores(String key, int indexDb) {
Set<Tuple> result = new HashSet<>();
Jedis jedis = getJedis();
if (jedis == null) {
return result;
}
try {
jedis.select(indexDb);
Set<Tuple> items = jedis.zrangeWithScores(key, 0, 1);
result = items;
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取String值
*
* @param key
* @return value
*/
public String getString(String key, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return "";
}
String returnStr = "";
try {
jedis.select(indexDb);
returnStr = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return returnStr;
}
/**
* 获取List值
*
* @param key
* @return value
*/
public String getListValue(String key, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return "";
}
String returnStr = "";
try {
jedis.select(indexDb);
returnStr = jedis.lpop(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return returnStr;
}
/**
* 获取List值 ,但是不移除队列
*
* @param key
* @return end
*/
public List<String> getListValueContext(String key, int indexDb) {
List<String> list = new ArrayList<String>();
Jedis jedis = getJedis();
if (jedis == null) {
return list;
}
try {
jedis.select(indexDb);
Long len = jedis.llen(key);
if (len <= 0)
return list;
list = jedis.lrange(key, 0, len);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return list;
}
// 删除list内指定值
public List<String> deleteIndex(String key, int indexDb, Long count, String value) {
List<String> list = new ArrayList<String>();
Jedis jedis = getJedis();
if (jedis == null) {
return list;
}
try {
jedis.select(indexDb);
jedis.lrem(key, count, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return list;
}
// 根据chanceuuid 删除
public boolean deletChanceByuuid(String key, int indexDb, String uuid) {
try {
List<String> list = new ArrayList<String>();
list = getListValueContext(key, indexDb);
if (!StringUtils.isNotBlank(uuid))
return true;
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).contains(uuid)) {
deleteIndex(key, indexDb, new Long(0), list.get(i).toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
// 根据索引删除
public boolean deletChanceByIndex(String key, int indexDb, int id) {
try {
List<String> list = new ArrayList<String>();
list = getListValueContext(key, indexDb);
if (null != String.valueOf(id))
return true;
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (i == id) {
deleteIndex(key, indexDb, new Long(0), list.get(i).toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 获取map值
*
* @param key
* @return value
*/
public String getMapValue(String key, String field, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return "";
}
String returnStr = "";
try {
jedis.select(indexDb);
returnStr = jedis.hget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return returnStr;
}
/**
* 获取map值
*
* @param key
* @return value
*/
public Long getMapLen(String key, int indexDb) {
Long size = 0L;
Jedis jedis = getJedis();
if (jedis == null) {
return size;
}
try {
jedis.select(indexDb);
size = jedis.hlen(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
return size;
}
/**
* 删除key
*
* @param key
* @return value
*/
public Long delKey(String key, int indexDb) {
Long size = 0L;
Jedis jedis = getJedis();
if (jedis == null) {
return size;
}
try {
jedis.select(indexDb);
size = jedis.del(key);
} catch (Exception e) {
// BaseLog.error("Redis delKey Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return size;
}
/**
* 删除匹配的key
*
* @param key
* @return value
*/
public Long delMatchKey(String key, int indexDb) {
Long size = 0L;
Jedis jedis = getJedis();
if (jedis == null) {
return size;
}
try {
jedis.select(indexDb);
Set<String> keys = jedis.keys(key.concat("*"));
if (null != keys && keys.size() > 0) {
for (String k : keys) {
size = jedis.del(k);
}
}
} catch (Exception e) {
// BaseLog.error("Redis delMatchKey Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return size;
}
/**
* 删除匹配的key
*
* @param key
* @return value
*/
// public Long delMatchKey(String key, int indexDb){
// Long size=0L;
// String cursor = ScanParams.SCAN_POINTER_START;
// Jedis jedis=getJedis();
// if(jedis== null){
// return size;
// }
// try {
// jedis.select(indexDb);
// ScanParams scanParams = new ScanParams();
// scanParams.match(key.concat("*"));// 匹配以 key * 为前缀的 key
// scanParams.count(1000);
// while (true){
// ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
// cursor = scanResult.getStringCursor();// 返回0 说明遍历完成
// List<String> result = scanResult.getResult();
// if(CollectionUtils.isNotEmpty(result)){
// for(int i =0;i<result.size();i++){
// String mapentry = result.get(i);
// //jedis.del(key, mapentry);
// jedis.ltrim(key, 0 ,1);
// }
// }
// if ("0".equals(cursor)){
// break;
// }
// }
// } catch (Exception e) {
// // BaseLog.error("getMapLen error : "+e);
// }
// finally{
// returnResource(jedis);
// }
// return size;
// }
/**
* 获取map值
*
* @param key
* @return value
*/
public Map<String, String> getMapValue(String key, String[] fields, int indexDb) {
Map<String, String> map = new HashMap<String, String>();
Jedis jedis = getJedis();
if (jedis == null) {
return map;
}
try {
jedis.select(indexDb);
for (String field : fields) {
String value = jedis.hget(key, field);
if (!StringUtils.isEmpty(value))
map.put(field, value);
else
map.put(field, "");
}
} catch (Exception e) {
// BaseLog.error("Redis getMapValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return map;
}
public boolean delMapValue(String key, String[] fields, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null || key == null || fields == null || indexDb < 0) {
return result;
}
try {
jedis.select(indexDb);
jedis.hdel(key, fields);
result = true;
} catch (Exception e) {
// BaseLog.error("Redis delMapValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public boolean delMapValueNew(String key, String[] fields, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return result;
}
try {
jedis.select(indexDb);
for (String field : fields) {
Boolean hexists = jedis.hexists(key, field);
if (hexists) {
jedis.hdel(key, field);
result = true;
}
}
result = true;
} catch (Exception e) {
// BaseLog.error("Redis delMapValueNew Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public boolean delSingleMapValue(String key, String fields, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return result;
}
try {
jedis.select(indexDb);
Boolean hexists = jedis.hexists(key, fields);
if (hexists) {
jedis.hdel(key, fields);
result = true;
}
} catch (Exception e) {
// BaseLog.error("jedis delSingleMapValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取map所有值
*
* @param key
* @return value
*/
public Map<String, String> getMapAllValue(String key, int indexDb) {
Map<String, String> map = new HashMap<String, String>();
Jedis jedis = getJedis();
if (jedis == null) {
return map;
}
try {
jedis.select(indexDb);
map = jedis.hgetAll(key);
} catch (Exception e) {
// BaseLog.error("Redis getMapAllValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return map;
}
/**
* 获取set所有值
*
* @param key
* @return value
*/
public Set<String> getSetAllValue(String key, int indexDb) {
Set<String> set = new HashSet<String>();
Jedis jedis = getJedis();
if (jedis == null) {
return set;
}
try {
jedis.select(indexDb);
set = jedis.smembers(key);
} catch (Exception e) {
// BaseLog.error("Redis getSetAllValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return set;
}
/**
* 获取set所有值
*
* @param key
* @return value
*/
public boolean setSetValue(String key, Collection<String> list, int seconds, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDb);
for (String value : list) {
jedis.sadd(key, value);
}
jedis.expire(key, seconds);
result = true;
} catch (Exception e) {
// BaseLog.error("Redis setSetValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取set所有值
*
* @param key
* @return value
*/
public boolean setSetValue(String key, List<String> list, int indexDb) {
boolean result = false;
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDb);
for (String value : list) {
jedis.sadd(key, value);
}
result = true;
} catch (Exception e) {
// BaseLog.error("Redis setSetValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取set所有值
*
* @param key
* @return value
*/
public boolean delSetValue(String key, List<String> list, int indexDb) {
Jedis jedis = null;
boolean flag = false;
try {
jedis = getJedis();
if (jedis == null) {
return false;
}
jedis.select(indexDb);
long count = 0;
for (String value : list) {
jedis.srem(key, value);
}
} catch (Exception ex) {
// BaseLog.error("Redis delSetValue Exception ");
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return true;
}
/**
* 设置map值
*
* @param key
* @return value
*/
public boolean setMapValue(String key, String field, String value, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
boolean result = false;
try {
jedis.select(indexDb);
jedis.hset(key, field, value);
result = true;
} catch (Exception e) {
// BaseLog.error("Redis setMapValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置map值
*
* @param key
* @return value
*/
public boolean setMapValue(String key, Map<String, String> map, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
boolean result = false;
try {
jedis.select(indexDb);
jedis.hmset(key, map);
result = true;
} catch (Exception e) {
// BaseLog.error("Redis setMapValue Exception ");
e.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
/**
* 判断key是否存在
*
* @param key
* @return value
*/
public boolean exists(String key, int indexDB) {
Jedis jedis = null;
boolean flag = false;
try {
jedis = getJedis();
if (jedis == null) {
return false;
}
jedis.select(indexDB);
flag = getJedis().exists(key);
} catch (Exception ex) {
// BaseLog.error("Redis exists Exception ");
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return flag;
}
/**
* 递增
*
* @param key
* @return value
*/
public boolean incr(String key, int expiredTime, int indexDB) {
Jedis jedis = getJedis();
if (jedis == null) {
return false;
}
boolean result = false;
try {
jedis.select(indexDB);
Transaction tx = jedis.multi();
tx.incr(key);
tx.expire(key, expiredTime);
tx.exec();
result = true;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return result;
}
public Long getListSize(String key, int indexDB) {
Long size = 0L;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return size;
}
try {
jedis.select(indexDB);
size = jedis.llen(key);
} catch (Exception ex) {
// BaseLog.error("Redis getListSize Exception ");
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return size;
}
public boolean pushList(String key, String value, int indexDB) {
boolean flag = false;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDB);
jedis.rpush(key, value);
flag = true;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return flag;
}
public String poplist(String key, int indexDB) {
String ret = "";
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return "";
}
try {
jedis.select(indexDB);
ret = jedis.lpop(key);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return ret;
}
// 命令用于将信息发送到指定的频道。
public boolean publish(String channel, String message, int indexDB) {
boolean flag = false;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDB);
jedis.publish(channel, message);
flag = true;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return flag;
}
public boolean rpush(String key, String message, int indexDB) {
boolean flag = false;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDB);
jedis.rpush(key, message);
flag = true;
} catch (Exception ex) {
// BaseLog.error("Redis rpush Exception ");
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return flag;
}
public Long llen(String key, int indexDB) {
Long total = Long.MAX_VALUE;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return Long.MAX_VALUE;
}
try {
jedis.select(indexDB);
total = jedis.llen(key);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return total;
}
/*public void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println("start:" + System.currentTimeMillis());
Jedis jedis = getJedis();
returnResource(jedis);
System.out.println("end:" + System.currentTimeMillis());
String string = jedis.toString();
System.out.println(string);
}
}*/
/**
* 获取锁
*
* @param lockId
* @param millisecond
* @return
*/
public boolean getLock(String lockId, int millisecond) {
Jedis jedis = null;
try {
jedis = getJedis();
Long lock = jedis.setnx(lockId, "lock");
jedis.expire(lockId, millisecond);
return lock == 1 ? true : false;
} finally {
returnResource(jedis);
}
}
/**
* 释放锁
*
* @param lockId
*/
public void releaseLock(String lockId) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(lockId);
} finally {
returnResource(jedis);
}
}
/**
* 用阻塞的方式从队列里面取值,如果没有值则会阻塞等待,超时后会抛出异常
*
* @param key
* @param timeOut
* @param indexDb
* @return
*/
public String blpop(String key, int timeOut, int indexDb) {
Jedis jedis = getJedis();
if (jedis == null) {
return "";
}
String str = "";
try {
jedis.select(indexDb);
List<String> list = jedis.blpop(timeOut, key);
if (CollectionUtils.isNotEmpty(list)) {
str = list.get(1);
} else {
str = "";
}
} catch (Exception e) {
// BaseLog.error("Redis getListValue Exception ");
e.printStackTrace();
return "";
} finally {
returnResource(jedis);
}
return str;
}
public boolean lpush(String key, String value, int indexDB) {
boolean flag = false;
Jedis jedis = null;
jedis = getJedis();
if (jedis == null) {
return false;
}
try {
jedis.select(indexDB);
jedis.lpush(key, value);
flag = true;
} catch (Exception ex) {
// BaseLog.error("Redis pushList Exception ");
ex.printStackTrace();
} finally {
returnResource(jedis);
}
return flag;
}
public void main(String[] args) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.lpush("fkk", "01");
jedis.lpush("fkk", "02");
List<String> currentNum = jedis.lrange("fkk", 0, -1);
List<String> currentNum2 = jedis.lrange("fkk", 0, -1);
System.out.println(currentNum);
System.out.println(currentNum2);
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
}
// 批量更新通配符键
public boolean setBatchKeyValue(String key, int indexDb, String value) {
try {
if (!StringUtils.isNotBlank(key)) return false;
Jedis jedis = getJedis();
jedis.select(indexDb);
Set<String> setKey = jedis.keys(key + "*");
if (setKey.size() > 0) {
for (String keyName : setKey) {
jedis.set(keyName, value);
}
}
} catch (Exception e) {
// BaseLog.error("Redis isExistInQueue Exception " );
e.printStackTrace();
}
return false;
}
}