JedisService:
package xyz.haijin.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.resps.Tuple;
import xyz.haijin.exception.RedisDataAccessException;
import xyz.haijin.utils.JedisPoolManager;
import xyz.haijin.vo.RedisHashVo;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
/**
* 2025/5/25.
* Redis操作服务类,基于Jedis客户端实现
*
* 提供对Redis的各种数据结构的操作,包括字符串、哈希、列表、集合、有序集合等
* 支持读写分离,通过readJedisPoolManager和writeJedisPoolManager分别管理读和写的连接池
*
* 主要功能包括:
* 1. 基本的键值操作(set/get/del/expire等)
* 2. 哈希表操作(hset/hget/hdel等)
* 3. 列表操作(lpush/rpush/lrange等)
* 4. 集合操作(sadd/smembers/srem等)
* 5. 有序集合操作(zadd/zrange/zrem等)
* 6. 发布订阅功能
* 7. Lua脚本支持
* 8. 管道批量操作
* 9. 分布式锁实现
*
* 注意事项:
* 1. 所有操作都自动管理Jedis连接的获取和释放
* 2. 读写操作使用不同的连接池
* 3. 大部分方法都进行了异常捕获,避免因Redis操作失败影响主流程
*
* @author haijin
*/
@Slf4j
@Service
public class JedisService {
private JedisPoolManager readJedisPoolManager;
private JedisPoolManager writeJedisPoolManager;
private static final String TOPIC = "TOPIC";
public JedisService(JedisPoolManager readJedisPoolManager, JedisPoolManager writeJedisPoolManager) {
Assert.notNull(readJedisPoolManager, "The readJedisPoolManager can't be null");
Assert.notNull(writeJedisPoolManager, "The writeJedisPoolManager can't be null");
this.readJedisPoolManager = readJedisPoolManager;
this.writeJedisPoolManager = writeJedisPoolManager;
}
public void setex(String key, int seconds, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.setex(key, seconds, value);
} catch (Exception e) {
log.error("setex from jedis error. key:{} value:{}", key, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Boolean setnx(String key, String value, Integer expireSeconds) {
Jedis wjedis = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
long result = wjedis.setnx(key, value);
if (result == 1) {
return Boolean.TRUE;
}
} catch (Exception e) {
log.error("zincrby from jedis error. key:{} score:{} member:{}", key);
} finally {
try {
wjedis.expire(key, expireSeconds);
} catch (Exception e) {
log.error("设置超时时间失败[key={}, value={},expireSeconds={}]", key, value, expireSeconds, e);
}
if (wjedis != null) {
wjedis.close();
}
}
return Boolean.FALSE;
}
public byte[] readByte(String key) throws RedisDataAccessException {
byte[] ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
byte[] jedisKey = key.getBytes();
byte[] content = rjedis.get(jedisKey);
if (content != null && content.length > 0) {
ret = content;
}
} catch (Exception e) {
log.error("read from jedis error. key:{} msg:{}", key, e);
throw new RedisDataAccessException("redis read error.", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
/**
* 写入redis,并指定失效时间点
*
* @param key
* @param content 数据
* @param deadLine 失效时间点
*/
public void write(String key, String content, Date deadLine) {
Jedis wjedis = null;
long now = System.currentTimeMillis();
long dead = deadLine.getTime();
int expireTime = (int) (dead - now) / (1000 * 60);//转换为分钟
if (expireTime <= 0) {
log.warn("request ignored .Date:{} msg:{}", new Object[]{deadLine, " invalid deadLine:The deadLine must be one minute later than currentTime "});
return;
} else {
try {
wjedis = writeJedisPoolManager.getJedis();
byte[] data = null;
if (content != null) {
data = content.getBytes();
}
byte[] jedisKey = key.getBytes();
wjedis.setex(jedisKey, expireTime, data);
} catch (Exception e) {
throw new RedisDataAccessException("redis read error.", e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
}
public void write(String key, byte[] content, int expireTime) throws RedisDataAccessException {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
byte[] data = content;
byte[] jedisKey = key.getBytes();
wjedis.setex(jedisKey, expireTime, data);
} catch (Exception e) {
throw new RedisDataAccessException("Failed to write key " + key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 写入redis,并指定失效时间点
*
* @param key
* @param content 数据
* @param expireTime 失效时长(秒)
*/
public void write(String key, String content, int expireTime) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
byte[] data = null;
if (content != null) {
data = content.getBytes();
}
byte[] jedisKey = key.getBytes();
wjedis.setex(jedisKey, expireTime, data);
} catch (Exception e) {
// log.error("write to jedis error. key:{} data:{} msg:{}", key, content, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void set(String key, String content) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.set(key, content);
} catch (Exception e) {
log.error("set to jedis error. key:{} data:{} msg:{}", key, content, e);
} finally {
if (wjedis != null) {
log.info("jedis set",wjedis);
wjedis.close();
log.info("jedis set",wjedis);
}
}
}
public void set(String key, String content, int expire) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.set(key, content);
if (expire >= 0) {
wjedis.expire(key, expire);
}
} catch (Exception e) {
log.error("set to jedis error. key:{} data:{} msg:{}", key, content, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void del(String key) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.del(key);
} catch (Exception e) {
log.error("delete from jedis error. key:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public String get(String key) {
String ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.get(key);
} catch (Exception e) {
log.error("get from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public String read(String key) {
String ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.get(key);
} catch (Exception e) {
log.error("hget from jedis error. key:{} field:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public Long incr(String key) {
Long wet = null;
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wet = wjedis.incr(key);
} catch (Exception e) {
log.error("incr from jedis error. key:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return wet;
}
public Long incrBy(String key, long inet) {
Long ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.incrBy(key, inet);
} catch (Exception e) {
log.error("incrBy from jedis error. key:{} inet:{}", key, inet);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public Double incrByFloat(String key, double inet) {
Double ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.incrByFloat(key, inet);
} catch (Exception e) {
log.error("incrBy from jedis error. key:{} inet:{}", key, inet);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public Long decr(String key) {
Long wet = null;
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wet = wjedis.decr(key);
} catch (Exception e) {
log.error("decr from jedis error. key:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return wet;
}
public Long decrBy(String key, long inet) {
Long ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.decrBy(key, inet);
} catch (Exception e) {
log.error("decrBy from jedis error. key:{} inet:{}", key, inet);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public void lpush(String key, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.lpush(key, value);
} catch (Exception e) {
log.error("lpush from jedis error. key:{} value:{}", key, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public String lpop(String key) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.lpop(key);
} catch (Exception e) {
log.error("rpop from jedis error. key:{} value:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
public String lindex(String key,Integer index) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.lindex(key,index);
} catch (Exception e) {
log.error("lIndex from jedis error. key:{} index:{}", key,index);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
public void rpush(String key, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.rpush(key, value);
} catch (Exception e) {
log.error("rpush from jedis error. key:{} value:{}", key, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Long llen(String key) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
return rjedis.llen(key);
} catch (Exception e) {
log.error("llen from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
public List<String> lrange(String key, long begin, long end) {
Jedis rjedis = null;
List<String> result = null;
try {
rjedis = readJedisPoolManager.getJedis();
result = rjedis.lrange(key, begin, end);
return result;
} catch (Exception e) {
log.error("llen from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
public Long lrem(String key, long count, String value) {
Jedis rjedis = null;
Long result = 0L;
try {
rjedis = readJedisPoolManager.getJedis();
result = rjedis.lrem(key, count, value);
return result;
} catch (Exception e) {
log.error("lrem from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return result;
}
public void ltrim(String key, long start, long end) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.ltrim(key, start, end);
} catch (Exception e) {
log.error("ltrim from jedis error. key:{} start:{} end ", key, start, end);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public String rpop(String key) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.rpop(key);
} catch (Exception e) {
log.error("rpop from jedis error. key:{} value:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
public String hget(String key, String field) {
String ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.hget(key, field);
} catch (Exception e) {
log.error("hget from jedis error. key=" + key + "field=" + field, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public void hset(String key, String field, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
Long hset = wjedis.hset(key, field, value);
} catch (Exception e) {
log.error("hset from jedis error. key:{} field:{} value:{}", key, field, value, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 将哈希表key中的域field的值设置为value,当且仅当域field不存在。
* 若域field已经存在,该操作无效。
* 如果key不存在,一个新哈希表被创建并执行HSETNX命令。
*
* @param key
* @param field
* @param value
* @return
* 设置成功,返回1。
* 如果给定域已经存在且没有操作被执行,返回0。
*/
public Long hsetnx(String key, String field, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.hsetnx(key, field, value);
} catch (Exception e) {
log.error("hset from jedis error. key:{} field:{} value:{}", key, field, value, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
public Boolean hexists(String key, String field) {
Boolean exists = false;
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
exists = wjedis.hexists(key,field);
} catch (Exception e) {
log.error("hexists from jedis error. key:{} field:{}", key, field, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return exists;
}
public List<String> hmread(String key, String... field) {
List<String> ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
if (field.length > 0) {
ret = rjedis.hmget(key, field);
}
} catch (Exception e) {
log.error("hmread from jedis error. key=" + key + "field=" + field, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public Map<String, String> hgetAll(String key) {
Map<String, String> ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.hgetAll(key);
} catch (Exception e) {
log.error("hget from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public List<String> hvals(String key){
List<String> vals = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
vals = rjedis.hvals(key);
} catch (Exception e) {
log.error("hvals from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return vals;
}
public Set<String> hgetAllKeysByKey(String key) {
Set<String> ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.hkeys(key);
} catch (Exception e) {
log.error("hreadAllByKey from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public Map<String, String> hgetAllBykey(String key) {
Map<String, String> ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.hgetAll(key);
} catch (Exception e) {
log.error("hreadAllByKey from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
public void hwrite(String key, String field, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hset(key, field, value);
} catch (Exception e) {
log.error("hwrite from jedis error. key:{} field:{} value:{}", key, field, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void hdelete(String key, String field, String value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hdel(key, field);
} catch (Exception e) {
log.error("hdelete from jedis error. key:{} field:{} value:{}", key, field, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void hdel(String key, String field) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hdel(key, field);
} catch (Exception e) {
log.error("hdel from jedis error. key:{} field:{} value:{}", key, field);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void hdel(String key, String... fields) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hdel(key, fields);
} catch (Exception e) {
log.error("hdel from jedis error. key:{} field:{} value:{}", key, fields);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Long hincr(String key, String field) {
return hincrBy(key, field, 1L);
}
public Long hincrBy(String key, String field, Long value) {
Jedis wjedis = null;
Long result = null;
try {
wjedis = writeJedisPoolManager.getJedis();
result = wjedis.hincrBy(key, field, value);
} catch (Exception e) {
log.error("hincrBy from jedis error. key:{} field:{} value:{}", key, field, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return result;
}
public void hdeleteKey(String key) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.del(key);
} catch (Exception e) {
log.error("delete from jedis error. key:{} field:{} value:{}", key);
if (wjedis != null) {
wjedis.close();
}
}
}
public void hwrite(String key, Map<String, String> value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hmset(key, value);
} catch (Exception e) {
log.error("hwrite from jedis error. key:{} value:{}", key, value);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* hmset 添加多条数据
* 删除key,重新设值,并且设置过期时间
* @param key
* @param map
* @param saveDate 单位为秒
*/
public void delAndHwriteAndExpire(String key, Map<String, String> map,int saveDate) {
Jedis wjedis = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Pipeline p = wjedis.pipelined();
p.del(key);
p.hmset(key,map);
p.expire(key,saveDate);
p.sync();
} catch (Exception e) {
log.error("delAndHwriteAndExpire from jedis error. key:{} value:{} member:{} saveDate:{}", key,map,saveDate);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void disableCache(String key) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.expire(key, 0);
} catch (Exception e) {
log.error("disableCache error. key:{} msg:{}", key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void remove(String key) throws RedisDataAccessException {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.del(key);
} catch (Exception e) {
log.error("remove error. key:{} msg:{}", key, e);
throw new RedisDataAccessException("Failed to remove key " + key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public void hincrbyfloat(String key, String property, double value) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
wjedis.hincrByFloat(key, property, value);
} catch (Exception e) {
log.error("hincrbyfloat from jedis error. key:=" + key + "&value=" + value, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Long ttl(String key) {
// key的剩余生存秒数,永久生存或者不存在的都返回-1
Jedis conn = null;
try {
// 获取连接
conn = writeJedisPoolManager.getJedis();
return conn.ttl(key);
} catch (JedisException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
return null;
}
public String lockWithTimeout(String locaName,
long acquireTimeout, long timeout) {
Jedis conn = null;
String retIdentifier = null;
String lockKey = null;
try {
// 获取连接
conn = writeJedisPoolManager.getJedis();
// 随机生成一个value
String identifier = UUID.randomUUID().toString();
// 锁名,即key值
lockKey = "lock:" + locaName;
// 超时时间,上锁后超过此时间则自动释放锁
int lockExpire = (int) (timeout / 1000);
// 获取锁的超时时间,超过这个时间则放弃获取锁
long end = System.currentTimeMillis() + acquireTimeout;
while (System.currentTimeMillis() < end) {
if (conn.setnx(lockKey, identifier) == 1) {
conn.expire(lockKey, lockExpire);
// 返回value值,用于释放锁时间确认
retIdentifier = identifier;
return retIdentifier;
}
// 返回-1代表key没有设置超时时间,为key设置一个超时时间
if (conn.ttl(lockKey) == -1) {
conn.expire(lockKey, lockExpire);
}
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
log.info("lock name: {}", lockKey);
if (conn != null) {
conn.close();
}
}
return retIdentifier;
}
/**
* 释放锁
*
* @param lockName 锁的key
* @param identifier 释放锁的标识
* @return
*/
public boolean releaseLock(String lockName, String identifier) {
Jedis conn = null;
String lockKey = "lock:" + lockName;
boolean retFlag = false;
try {
conn = writeJedisPoolManager.getJedis();
while (true) {
// 监视lock,准备开始事务
conn.watch(lockKey);
// 通过前面返回的value值判断是不是该锁,若是该锁,则删除,释放锁
if (identifier.equals(conn.get(lockKey))) {
Transaction transaction = conn.multi();
transaction.del(lockKey);
List<Object> results = transaction.exec();
if (results == null) {
continue;
}
retFlag = true;
}
conn.unwatch();
break;
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
// log.info("锁名称:" + lockKey);
if (conn != null) {
conn.close();
}
}
return retFlag;
}
public Double zincrby(String key, Double score, String member) {
Jedis wjedis = null;
Double totalScore = 0D;
try {
wjedis = this.writeJedisPoolManager.getJedis();
totalScore = wjedis.zincrby(key, score, member);
} catch (Exception e) {
log.error("zincrby from jedis error. key:{} score:{} member:{}", key, score, member);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return totalScore;
}
public void zadd(String key, Double score, String member) {
Jedis wjedis = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
wjedis.zadd(key, score, member);
} catch (Exception e) {
log.error("zincrby from jedis error. key:{} score:{} member:{}", key, score, member);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Long zrem(String key, String member) {
Jedis wjedis = null;
Long amount = 0L;
try {
wjedis = this.writeJedisPoolManager.getJedis();
amount = wjedis.zrem(key, member);
} catch (Exception e) {
log.error("zrem from jedis error. key:{} , member:{}", key, member);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return amount;
}
public Long zremrangeByScore(String key, double start, double end) {
Jedis wjedis = null;
Long amount = 0L;
try {
wjedis = this.writeJedisPoolManager.getJedis();
amount = wjedis.zremrangeByScore(key, start, end);
} catch (Exception e) {
log.error("zremrangeByScore from jedis error. key:{} , start:{} , end:{}", key, start, end);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return amount;
}
public List<Map<String, Object>> zrevrange(String key, Long begin, Long end) {
Jedis rjedis = null;
List<Map<String, Object>> set = new ArrayList<>();
try {
rjedis = this.readJedisPoolManager.getJedis();
List<Tuple> tuples = rjedis.zrevrangeWithScores(key, begin, end);
for (Tuple tuple : tuples) {
Map<String, Object> map = Maps.newHashMap();
map.put("member", tuple.getElement());
map.put("score", tuple.getScore());
set.add(map);
}
} catch (Exception e) {
log.error("zrevrange from redis error. key:{}, begin:{}, end:{}", key, begin, end, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return set;
}
public List<String> zrevrangeVals(String key, Long begin, Long end) {
Jedis rjedis = null;
List<String> set =null;
try {
rjedis = this.readJedisPoolManager.getJedis();
set = rjedis.zrevrange(key, begin, end);
} catch (Exception e) {
log.error("zrevrange from redis error. key:{}, begin:{}, end:{}", key, begin, end, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return set;
}
/**
* 获取sorted set指定区间数据,按score从低到高
*
* @param key
* @param begin
* @param end
* @return
*/
public List<Map<String, Object>> zrange(String key, Integer begin, Integer end) {
Jedis rjedis = null;
List<Map<String, Object>> set = new ArrayList<>();
try {
rjedis = this.readJedisPoolManager.getJedis();
List<Tuple> tuples = rjedis.zrangeWithScores(key, begin, end);
for (Tuple tuple : tuples) {
Map<String, Object> map = Maps.newHashMap();
map.put("member", tuple.getElement());
map.put("score", tuple.getScore());
set.add(map);
}
} catch (Exception e) {
log.error("zrange from redis error. key:{}, begin:{}, end:{}", key, begin, end, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return set;
}
/**
* 获取sorted set中成员排名,按score从低到高
*
* @param key
* @param member
* @return
*/
public Long zrank(String key, String member) {
Jedis rjedis = null;
Long ranking = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
ranking = rjedis.zrank(key, member);
} catch (Exception e) {
log.error("zrank from redis error. key:{}, member:{}", key, member, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ranking;
}
/**
* 获取sorted set中成员排名,从高到低
*
* @param key
* @param member
* @return
*/
public Long zrevrank(String key, String member) {
Jedis rjedis = null;
Long ranking = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
ranking = rjedis.zrevrank(key, member);
} catch (Exception e) {
log.error("zrevrank from redis error. key:{}, member:{}", key, member, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ranking;
}
/**
* 获取sorted set中成员score
*
* @param key
* @param member
* @return
*/
public Double zscore(String key, String member) {
Jedis rjedis = null;
Double ranking = new Double(0);
try {
rjedis = this.readJedisPoolManager.getJedis();
ranking = rjedis.zscore(key, member);
} catch (Exception e) {
log.error("zrevrank from redis error. key:{}, member:{}", key, member, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ranking;
}
/**
* 获取sorted set中成员score
*
* @param key
* @return
*/
public Long zcard(String key) {
Jedis rjedis = null;
Long size = 0L;
try {
rjedis = this.readJedisPoolManager.getJedis();
size = rjedis.zcard(key);
} catch (Exception e) {
log.error("zcard from redis error. key:{}, member:{}", key, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return size;
}
/**
* 设置key过期时间
*
* @param key
* @param seconds
* @return
*/
public Boolean expire(String key, Integer seconds) {
Jedis wjedis = null;
Long size = 0L;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Long result = wjedis.expire(key, seconds);
return result == 1;
} catch (Exception e) {
log.error("expire from redis error. key:{}, member:{}", key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return false;
}
/**
* 设置key过期时间
*
* @param key
* @param seconds 到期时间
* @return
*/
public Boolean expireAt(String key, Long seconds) {
Jedis wjedis = null;
Long size = 0L;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Long result = wjedis.expireAt(key, seconds);
return result == 1 ? true : false;
} catch (Exception e) {
log.error("expire from redis error. key:{}, member:{}", key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return false;
}
/**
* 设置key过期时间
*
* @param key
* @param millis 到期时间
* @return
*/
public Boolean pexpireAt(String key, Long millis) {
Jedis wjedis = null;
Long size = 0L;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Long result = wjedis.pexpireAt(key, millis);
return result == 1 ? true : false;
} catch (Exception e) {
log.error("expire from redis error. key:{}, member:{}", key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return false;
}
/**
* 获取sorted set指定区间member数据
*
* @param key
* @param begin
* @param end
* @return
*/
public List<String> zrangeMembers(String key, Integer begin, Integer end) {
Jedis rjedis = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
List<String> sets = rjedis.zrange(key, begin, end);
return sets;
} catch (Exception e) {
log.error("zrange from redis error. key:{}, begin:{}, end:{}", key, begin, end, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
/**
* 添加sorted数据 同时限制大小
*
* @param key
* @param score
* @param member
* @param limitSize
*/
public void zaddLimit(String key, double score, String member, int limitSize) {
Jedis rjedis = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
Pipeline p = rjedis.pipelined();
p.zadd(key, score, member);
p.zremrangeByRank(key, limitSize, -1);
p.sync();
} catch (Exception e) {
log.error("zaddLimit from redis error. key:{},e{}", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
}
/**
* 添加sorted数据 同时限制大小
*
* @param key
* @param map
* @param limitSize
*/
public void zaddLimit(String key, Map<String, Double> map, int limitSize) {
Jedis rjedis = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
Pipeline p = rjedis.pipelined();
p.zadd(key, map);
p.zremrangeByRank(key, limitSize, -1);
p.sync();
} catch (Exception e) {
log.error("zaddLimit from redis error. key:{},e{}", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
}
/**
* zset 添加多条数据
*/
public void zadd(String key, Map<String, Double> map, boolean clean) {
Jedis wjedis = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Pipeline p = wjedis.pipelined();
if (clean) {
p.zremrangeByRank(key, 0, -1);
}
p.zadd(key, map);
p.sync();
} catch (Exception e) {
log.error("zincrby from jedis error. key:{} score:{} member:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 通过redis的Pipeline 批量添加list数据
*/
public boolean lpushList(String key, List<?> list) {
Jedis wjedis = null;
boolean status = false;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Pipeline p = wjedis.pipelined();
if (list != null && !list.isEmpty()) {
for (Object el : list) {
p.lpush(key, String.valueOf(el));
}
}
p.sync();
status = true;
return status;
} catch (Exception e) {
log.error("lpushList from jedis error. key:{} list:{}", key, list);
return status;
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 通过redis的Pipeline 批量添加list数据
*/
public boolean rpushList(String key, List<?> list) {
Jedis wjedis = null;
boolean status = false;
try {
wjedis = this.writeJedisPoolManager.getJedis();
Pipeline p = wjedis.pipelined();
if (list != null && !list.isEmpty()) {
for (Object el : list) {
p.rpush(key, String.valueOf(el));
}
}
p.sync();
status = true;
return status;
} catch (Exception e) {
log.error("rpushList from jedis error. key:{} list:{}", key, list);
return status;
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 通过redis的Pipeline 批量添加Set数据
*/
public boolean saddSet(String key, List<?> list) {
Jedis wjedis = null;
boolean status = false;
try {
wjedis = this.writeJedisPoolManager.getJedis();
if (list != null && !list.isEmpty()) {
// 去重
Set<?> set = new HashSet<>(list);
Pipeline p = wjedis.pipelined();
for (Object el : set) {
p.sadd(key, String.valueOf(el));
}
p.sync();
}
status = true;
return status;
} catch (Exception e) {
log.error("lpushList from jedis error. key:{} list:{}", key, list);
return status;
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 返回指定权重区间的元素集合
*
* @param key
* @param min 上限权重
* @param max 下限权重z
* @return Set<String>
*/
public List<String> zrangeByScore(String key, String min, String max) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
List<String> set = rjedis.zrangeByScore(key, min, max);
return set;
} catch (Exception e) {
log.error("zrangeByScore from jedis error. key:{} min:{} max:{}", key, min, max);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
public List<String> zrangeByScore(String key, double min, double max) {
Jedis rjedis = null;
try {
rjedis = this.readJedisPoolManager.getJedis();
List<String> set = rjedis.zrangeByScore(key, min, max);
List var8 = set;
return var8;
} catch (Exception var12) {
log.error("zrangeByScore from jedis error. key:{} min:{} max:{}", new Object[]{key, min, max});
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
public Set<String> smembers(String key) {
Jedis rjedis = null;
Set<String> result = null;
try {
rjedis = readJedisPoolManager.getJedis();
result = rjedis.smembers(key);
return result;
} catch (Exception e) {
log.error("llen from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
/**
* 执行脚本
*/
public Object eval(String script, int keyCount, String... params) {
Jedis wjedis = null;
Object result = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
result = wjedis.eval(script, keyCount, params);
} catch (Exception e) {
log.error("eval from jedis error params:{},e:{}", params,e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return result;
}
/**
* 确定一个给定的值是否存在
*
* @param key
* @param member
* @return
*/
public boolean sismember(String key, String member) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
boolean s = rjedis.sismember(key, member);
return s;
} catch (Exception e) {
log.error("sismember from jedis error. key:{} member:{}", key, member);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return false;
}
/**
* 向Set添加一条记录,如果member已存在返回0,否则返回1
*
* @param key
* @param member
* @return
*/
public long sadd(String key, String member) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.sadd(key, member);
} catch (Exception e) {
log.error("sadd from jedis error. key:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return 0;
}
/**
* 检测key是否存在
*
* @param key
* @return
*/
public Boolean exits(String key) {
Jedis wjedis = null;
try {
wjedis = this.writeJedisPoolManager.getJedis();
return wjedis.exists(key);
} catch (Exception e) {
log.error("expire from redis error. key:{}, member:{}", key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return false;
}
/**
* 从集合中删除指定成员
*
* @param key
* @param member
* @return
*/
public Long srem(String key, String member) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.srem(key, member);
} catch (Exception e) {
log.error("srem from jedis error. key:{}", key);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return 0L;
}
/**
* 批量删除redisKey
* @param key
* @throws RedisDataAccessException
*/
public void batchRemove(String key) throws RedisDataAccessException {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
Set<String> set = wjedis.keys(key + "*");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String keyStr = it.next();
System.out.println(keyStr);
wjedis.del(keyStr);
}
} catch (Exception e) {
log.error("batchRemove error. key:{} msg:{}", key, e);
throw new RedisDataAccessException("Failed to batchRemove key " + key, e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 批量删除key
* @param keys
* @throws RedisDataAccessException
*/
public void batchRemoveKey(String... keys) throws RedisDataAccessException {
Jedis wjedis = null;
try {
if(keys.length>0) {
wjedis = writeJedisPoolManager.getJedis();
Pipeline p = wjedis.pipelined();
for (String key : keys) {
p.del(key);
}
p.sync();
}
} catch (Exception e) {
log.error("batchRemoveKey error. key:{}", keys);
throw new RedisDataAccessException("Failed to batchRemoveKey key " + keys);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
/**
* 执行lua脚本
*
* @param scriptSha
* @param keys
* @param args
* @return
*/
public Object evalsha(String scriptSha, List<String> keys, List<String> args) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.evalsha(scriptSha, keys, args);
} catch (Exception e) {
log.error("evalScript fail.", e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
/**
* 加载lua脚本
*
* @param script
* @return
*/
public String scriptLoad(String script) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
return wjedis.scriptLoad(script);
} catch (Exception e) {
log.error("scriptLoad fail.", e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
return null;
}
/**
* 批量写入
*
* @param key
* @param jsonObject
*/
public void hsetBatch(String key, JSONObject jsonObject) {
Jedis wjedis = null;
try {
wjedis = writeJedisPoolManager.getJedis();
Pipeline pipeline = wjedis.pipelined();
List<JSONObject> jsonObjectList = new ArrayList<>();
jsonObject.forEach((itemKey, itemValue) ->
{
jsonObjectList.add((JSONObject) itemValue);
pipeline.hset(key, itemKey, JSONObject.toJSONString(itemValue));
});
pipeline.sync();
pipeline.close();
} catch (Exception e) {
log.error("hsetBatch fail.", e);
} finally {
if (wjedis != null) {
wjedis.close();
}
}
}
public Long hlen(String key) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
return rjedis.hlen(key);
} catch (Exception e) {
log.error("hlen from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
public void rename(String key, String newKey) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
rjedis.rename(key, newKey);
} catch (Exception e) {
log.error("rename from jedis error. key:{}, newkey:{}, error:{}", key, newKey, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
}
/**
* 发布消息
* @param channel
* @param message
*/
public void publish(String channel ,String message) {
Jedis rjedis = null;
if (StringUtils.isBlank(channel)){
channel = TOPIC;
}
try {
rjedis = readJedisPoolManager.getJedis();
rjedis.publish(channel, message);
} catch (Exception e) {
log.error("publish from jedis error. channel:{}, messge:{}, error:{}", channel, message, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
}
/**
* 订阅消息
* @param channel
* @param jedisPubSub
*/
public void subscribe(String channel, JedisPubSub jedisPubSub) {
Jedis rjedis = null;
if (StringUtils.isBlank(channel)){
channel = TOPIC;
}
try {
rjedis = readJedisPoolManager.getJedis();
rjedis.subscribe(jedisPubSub, channel);
} catch (Exception e) {
log.error("subscribe from jedis error. channel:{}, jedisPubSub:{}, error:{}", channel, JSON.toJSONString(jedisPubSub), e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
}
/**
* 批量获取
*/
public List<RedisHashVo> hgetBatch(List<RedisHashVo> voList) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
Pipeline pipeline = rjedis.pipelined();
voList.stream().filter(vo -> vo.getField() != null)
.forEach(vo -> {
Response<String> hget = pipeline.hget(vo.getKey(), vo.getField());
vo.setResponse(hget);
});
pipeline.sync();
pipeline.close();
voList.forEach(vo ->
vo.setValue(Optional.ofNullable(vo.getResponse()).map(resp -> resp.get()).orElse(null))
);
return voList;
} catch (Exception e) {
log.error("hgetBatch from jedis error", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return voList;
}
/**
* @description 随机获取一个元素
* @author qiudonglin
* @date 2020/3/19/0019
*/
public List<String> srandmember(String key, int count) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
return rjedis.srandmember(key, count);
} catch (Exception e) {
log.error("srandmember from jedis error. ", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
/**
* @description 随机删除一个元素,并返回
* @author qiudonglin
* @date 2020/3/26/0026
* @return
*/
public Set<String> spop(String key, int count) {
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
return rjedis.spop(key, count);
} catch (Exception e) {
log.error("spop from jedis error. ", e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return null;
}
/**
* 在管道执行
*
* @param consumer
* @throws IOException
*/
public void doInPipeline(Consumer<Pipeline> consumer) throws IOException {
final Jedis jedis = writeJedisPoolManager.getJedis();
final Pipeline pipeline = jedis.pipelined();
try {
consumer.accept(pipeline);
pipeline.sync();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public Set<Map<String, Object>> zrevrangeWithScore(String key, Long begin, Long end) {
Jedis rjedis = null;
LinkedHashSet set = Sets.newLinkedHashSet();
try {
rjedis = this.readJedisPoolManager.getJedis();
List<Tuple> tuples = rjedis.zrevrangeWithScores(key, begin, end);
Iterator var7 = tuples.iterator();
while(var7.hasNext()) {
Tuple tuple = (Tuple)var7.next();
Map<String, Object> map = Maps.newHashMap();
map.put("member", tuple.getElement());
map.put("score", tuple.getScore());
set.add(map);
}
} catch (Exception var13) {
log.error("zrevrange from redis error. key:{}, begin:{}, end:{}", new Object[]{key, begin, end, var13});
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return set;
}
/**
* 获取 set中成员数
*
* @param key
* @return
*/
public Long scard(String key) {
Jedis rjedis = null;
Long size = 0L;
try {
rjedis = this.readJedisPoolManager.getJedis();
size = rjedis.scard(key);
} catch (Exception e) {
log.error("scard from redis error. key:{}, member:{}", key, e);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return size;
}
public Set<String> getAllKeys(String key) {
Set<String> ret = null;
Jedis rjedis = null;
try {
rjedis = readJedisPoolManager.getJedis();
ret = rjedis.keys(key);
} catch (Exception e) {
log.error("hreadAllByKey from jedis error. key:{}", key);
} finally {
if (rjedis != null) {
rjedis.close();
}
}
return ret;
}
}