使用Jedis操作redis常用的方法汇总:
public abstract class RedisCacheTemplate {
private static final Logger logger = LoggerFactory.getLogger(RedisCacheTemplate.class);
public abstract Jedis getJedis();
public abstract Jedis getSentinelJedis();
public Map<String, String> hgetAll(String key) {
Jedis jedis = getJedis();
try {
Map<String, String> value = jedis.hgetAll(key);
return value;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public <T> T get(String key, Class<T> clazz) {
Jedis jedis = getJedis();
try {
String value = jedis.get(key);
if (clazz.newInstance() instanceof String) {
return (T) value;
}
return JsonUtil.parseObject(value, clazz);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public <T> T getSentinel(String key, Class<T> clazz) {
Jedis jedis = getSentinelJedis();
try {
String value = jedis.get(key);
if (clazz.newInstance() instanceof String) {
return (T) value;
}
return JsonUtil.parseObject(value, clazz);
} catch (Exception e) {
logger.error("getSentinel key:{},error msg:{},error:{}", key, e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public <T> List<T> getList(String key, Class<T> clazz) {
Jedis jedis = getJedis();
try {
return JsonUtil.parseArray(jedis.get(key), clazz);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public <T> List<T> getListFromQueue(String key, Integer number, Class<T> clazz) {
Jedis jedis = getJedis();
try {
Pipeline pipeline = jedis.pipelined();
Response<List<String>> responses = pipeline.lrange(key, 0, number - 1);
pipeline.ltrim(key, number, -1);
pipeline.sync();
if (responses != null) {
List<String> list = responses.get();
return JSONObject.parseArray(list.toString(), clazz);
}
} catch (Exception e) {
logger.error("redis 获取队列数据异常:" + e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 获取缓存值列表
*
* @param key
* @param clazz
* @return
*/
@Override
public <T> Map<String, List<T>> getMapArray(String key, Class<T> clazz) {
Jedis jedis = getJedis();
try {
Map<String, JSONArray> maps = this.get(key, Map.class);
Map<String, List<T>> conventResult = null;
if (maps != null && maps.size() > 0) {
conventResult = new HashMap<>(maps.size());
Iterator<String> iterator = maps.keySet().iterator();
String mapKey;
while (iterator.hasNext()) {
mapKey = iterator.next();
List<T> arrays = JsonUtil.parseArray(maps.get(mapKey).toJSONString(), clazz);
conventResult.put(mapKey, arrays);
}
}
return conventResult;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 获取缓存值列表
*
* @param key
* @param clazz
* @return
*/
@Override
public <T> Map<String, T> getMap(String key, Class<T> clazz) {
Jedis jedis = getJedis();
try {
Map<String, JSONObject> maps = this.get(key, Map.class);
Map<String, T> conventResult = null;
if (maps != null && maps.size() > 0) {
conventResult = new HashMap<>(maps.size());
Iterator<String> iterator = maps.keySet().iterator();
String mapKey;
while (iterator.hasNext()) {
mapKey = iterator.next();
if (clazz == String.class) {
conventResult.put(mapKey, (T) maps.get(mapKey));
} else {
conventResult.put(mapKey, JsonUtil.parseObject(maps.get(mapKey).toJSONString(), clazz));
}
}
}
return conventResult;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public <T> void set(String key, T value, Integer timeout) {
Jedis jedis = getJedis();
try {
String data = "";
if (value instanceof String) {
data = (String) value;
} else {
data = JsonUtil.toString(value);
}
jedis.setex(key, timeout, data);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
//20200927 add by jzy 将redis单点改为哨兵模式
@Override
public <T> void setSentinel(String key, T value, Integer timeout) {
Jedis jedis = getSentinelJedis();
try {
String data = "";
if (value instanceof String) {
data = (String) value;
} else {
data = JsonUtil.toString(value);
}
jedis.setex(key, timeout, data);
logger.info("setSentinel key:{},timeout:{},data:{}", key, timeout, data);
} catch (Exception e) {
logger.error("setSentinel key:{},error msg:{},error:{}", key, e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 储存缓存值
*
* @param key
* @param value
*/
@Override
public <T> void set(String key, T value) {
Jedis jedis = getJedis();
try {
String data = "";
if (value instanceof String) {
data = (String) value;
} else {
data = JsonUtil.toString(value);
}
jedis.set(key, data);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 20200927 add by jzy 将redis单点改为哨兵模式
* 储存缓存值
*
* @param key
* @param value
*/
@Override
public <T> void setSentinel(String key, T value) {
Jedis jedis = getSentinelJedis();
try {
String data = "";
if (value instanceof String) {
data = (String) value;
} else {
data = JsonUtil.toString(value);
}
jedis.set(key, data);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void remove(String key) {
Jedis jedis = getJedis();
try {
jedis.del(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
//20200927 add by jzy 将redis单点改为哨兵模式
@Override
public void removeSentinel(String key) {
Jedis jedis = getSentinelJedis();
try {
jedis.del(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void removeLike(String key) {
Jedis jedis = getJedis();
try {
Set<String> keys = jedis.keys(key + "*");
if (!CollectionUtils.isEmpty(keys)) {
jedis.del(keys.toArray(new String[keys.size()]));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public Boolean exists(String key) {
Jedis jedis = getJedis();
try {
return jedis.exists(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
//20200927 add by jzy 将redis单点改为哨兵模式
@Override
public Boolean existsSentinel(String key) {
Jedis jedis = getSentinelJedis();
try {
return jedis.exists(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
@Override
public Long getSequence(String key) {
Jedis jedis = getJedis();
try {
// 超时时间为1小时
int timeout = 3600;
Long seq = jedis.incr(key);
jedis.expire(key, timeout);
// 14位日期+4位数字
StringBuilder builder = new StringBuilder();
builder.append(DateUtil.getNow(DateUtil.longFormat));
builder.append(StringUtils.leftPad(String.valueOf(seq), 4, '0'));
return Long.valueOf(builder.toString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public String sPop(String key) {
Jedis jedis = getJedis();
try {
return jedis.spop(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public void sAdd(String key, String... item) {
Jedis jedis = getJedis();
try {
jedis.sadd(key, item);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public Long sCard(String key) {
Jedis jedis = getJedis();
try {
return jedis.scard(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Set<String> sMembers(String key) {
Jedis jedis = getJedis();
try {
return jedis.smembers(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return new HashSet<>();
}
@Override
public byte[] getByte(byte[] key) {
Jedis jedis = getJedis();
try {
return jedis.get(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public void lPush(String key, String value) {
Jedis jedis = getJedis();
try {
jedis.lpush(key, value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void rPush(String key, String value) {
Jedis jedis = getJedis();
try {
jedis.rpush(key, value);
} catch (Exception e) {
logger.error("队列添加数据失败:" + e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void rPushSentinel(String key, String value) {
Jedis jedis = getSentinelJedis();
try {
jedis.rpush(key, value);
} catch (Exception e) {
logger.error("队列添加数据失败:" + e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public <T> void rPushList(List<T> value, String key) {
if (CollectionUtils.isEmpty(value)) {
return;
}
Jedis jedis = getJedis();
try {
Pipeline pipeline = jedis.pipelined();
for (T v : value) {
pipeline.rpush(key, JSONObject.toJSONString(v));
}
pipeline.sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public String lPop(String key) {
Jedis jedis = getJedis();
try {
return jedis.lpop(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Long lLen(String key) {
Jedis jedis = getJedis();
try {
return jedis.llen(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Long incr(String key) {
Jedis jedis = getJedis();
try {
return jedis.incr(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Long incrSentinel(String key) {
Jedis jedis = getSentinelJedis();
try {
return jedis.incr(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Long decr(String key) {
Jedis jedis = getJedis();
try {
return jedis.decr(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public void expire(String key, int seconds) {
Jedis jedis = getJedis();
try {
jedis.expire(key, seconds);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void expireSentinel(String key, int seconds) {
Jedis jedis = getSentinelJedis();
try {
jedis.expire(key, seconds);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void expireBytesKey(byte[] key, int expire) {
Jedis jedis = getJedis();
try {
jedis.expire(key, expire);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public Long pTtl(String key) {
Jedis jedis = getJedis();
try {
return jedis.pttl(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public String lIndex(String key, Long index) {
Jedis jedis = getJedis();
try {
return jedis.lindex(key, index);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@Override
public Long incr(String key, Integer num) {
Jedis jedis = getJedis();
try {
return jedis.incrBy(key, num);
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
@Override
public Set<String> keyLike(String key) {
Jedis jedis = getJedis();
try {
Set<String> keys = jedis.keys("*" + key + "*");
return keys;
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
@Override
public Long geoAdd(String key, Double lng, Double lat, String member) {
Jedis jedis = getJedis();
try {
return jedis.geoadd(key, lng, lat, member);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public List<GeoCoordinate> geoPos(String key, String... member) {
Jedis jedis = getJedis();
try {
List<GeoCoordinate> list = jedis.geopos(key, member);
return list;
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Double geoDist(String key, String startMember, String endMember) {
Jedis jedis = getJedis();
try {
return jedis.geodist(key, startMember, endMember);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public List<GeoRadiusResponse> geoRadius(String key, double longitude, double latitude, double radius) {
Jedis jedis = getJedis();
try {
GeoRadiusParam param = GeoRadiusParam.geoRadiusParam();
param.withCoord();
param.withDist();
return jedis.georadius(key, longitude, latitude, radius, GeoUnit.M, param);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public List<GeoRadiusResponse> geoRadiusMember(String key, String member, double radius) {
Jedis jedis = getJedis();
try {
return jedis.georadiusByMember(key, member, radius, GeoUnit.M);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public List<String> geoHash(String key, String... members) {
Jedis jedis = getJedis();
try {
return jedis.geohash(key, members);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Long zRem(String key, String... members) {
Jedis jedis = getJedis();
try {
return jedis.zrem(key, members);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Long zAdd(String key, Double score, String member) {
Jedis jedis = getJedis();
try {
return jedis.zadd(key, score, member);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Set<String> zRange(String key, long start, long end) {
Jedis jedis = getJedis();
try {
return jedis.zrange(key, start, end);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Set<Tuple> zRangeWithScores(String key, long start, long end) {
Jedis jedis = getJedis();
try {
return jedis.zrangeWithScores(key, start, end);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Set<Tuple> zRangeByScoreWithScores(String key, double min, double max) {
Jedis jedis = getJedis();
try {
return jedis.zrangeByScoreWithScores(key, min, max);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Set<String> zRangeByScore(String key, double min, double max) {
Jedis jedis = getJedis();
try {
return jedis.zrangeByScore(key, min, max);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Long zRemRangeByScore(String key, double min, double max) {
Jedis jedis = getJedis();
try {
return jedis.zremrangeByScore(key, min, max);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Long addNewString(String key, String value) {
Jedis jedis = getJedis();
try {
return jedis.setnx(key, value);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public Long addHashMap(String key, String field, String value) {
Jedis jedis = getJedis();
try {
return jedis.hset(key, field, value);
} catch (Exception e) {
throw e;
} finally {
if (null != jedis) {
jedis.close();
}
}
}
@Override
public void delKeys(List<String> ids) {
if (CollectionUtils.isEmpty(ids)) {
return;
}
String[] idArr = ids.toArray(new String[0]);
Jedis jedis = getJedis();
try {
jedis.del(idArr);
} catch (Exception e) {
logger.error("删除redis key 异常:", e);
} finally {
if (null != jedis) {
jedis.close();
}
}
}
}