import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import com.cjr.onlinecredit.redis.component.JedisTemplate;
import com.cjr.onlinecredit.utils.BaseUtils;
import com.cjr.onlinecredit.utils.json.JsonUtils;
/**
* redis辅助类
*
* key的命名规则
* 模块名_业务
* 例如:ETT_LIST_ETT
*
*/
public final class JedisUtils extends BaseUtils {
private static Logger log = LoggerFactory.getLogger(JedisUtils.class);
private static final TimeUnit TU_SECOND = TimeUnit.SECONDS;
//=============单对象处理类型函数==================
/**
* 设置 String
* @param key
* @param value
*/
public static boolean set(String key, String value) {
return set(key, value, -1);
}
/**
* 设置 String
* @param key
* @param value
*/
public static boolean set(String key, int value) {
return set(key, value, -1);
}
/**
* 设置 过期时间
* @param key
* @param value
* @param seconds 以秒为单位
*/
public static boolean set(String key, String value, long seconds) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
value = isNull(value) ? "" : value;
if (seconds <= 0) {
redisTemplate.opsForValue().set(key, value);
} else {//需要设置时间的
redisTemplate.opsForValue().set(key, value, seconds, TU_SECOND);
}
} catch (Exception e) {
log.error("====redis====set key[" + key + "] value[\"+JsonUtils.toJson(value)+\"] error : [" + e.getMessage() + "]====");
return false;
} finally {
// ==== 把资源交还回连接池
}
return true;
}
/**
* 设置 单个对象
* @param key
* @param value
*/
public static <T> boolean set(String key, T value) {
return set(key, value, -1);
}
/**
* 设置 过期时间
* @param key
* @param value
* @param seconds 以秒为单位
*/
public static <T> boolean set(String key, T value, long seconds) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
if (isNull(value))
return false;
if (seconds <= 0) {
redisTemplate.opsForValue().set(key, value);
} else {//需要设置时间的
redisTemplate.opsForValue().set(key, value, seconds, TU_SECOND);
}
} catch (Exception e) {
log.error("====redis====set key[" + key + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return false;
} finally {
// ==== 把资源交还回连接池
}
return true;
}
/**
* 获取key值
* @param key
* @return value
*/
public static String get(String key) {
String value = "";
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return value;
}
//== 检查key是否有效 即是否过期
if (!isValidKey(key)) {
delKey(key);//删除
return value;
}
Object v = redisTemplate.opsForValue().get(key);
value = null2string(v);
} catch (Exception e) {
log.error("====redis====get key[" + key + "] error : [" + e.getMessage() + "]====");
} finally {
// ==== 把资源交还回连接池
}
return value;
}
/**
* 获取key值
* @param key
* @return value
*/
@SuppressWarnings("unchecked")
public static <T> T getObj(String key) {
T value = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return value;
}
//== 查询有效时间
if (!isValidKey(key)) {
delKey(key);//删除
return value;
}
//==获取数据
Object obj = redisTemplate.opsForValue().get(key);
if (obj != null)
value = (T) obj;
} catch (Exception e) {
log.error("====redis====getObj key[" + key + "] error : [" + e.getMessage() + "]====");
} finally {
// ==== 把资源交还回连接池
}
return value;
}
/**
* 查找与指定模式匹配的所有键
*
* @param key
* @return
*/
public static Set<String> keys(String key) {
if (isNull(key))
return null;
Set<String> keys = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return keys;
keys = redisTemplate.keys(key);
} catch (Exception e) {
log.error("====redis====keys key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return keys;
}
/**
* 删除键
* 删除后 所有值全部消失
* @param key
* @return
*/
public static boolean delKey(String key) {
if (isNull(key))
return false;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.delete(key);
} catch (Exception e) {
log.error("====redis====delKey key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 设置有效时间
* @param key
* @param seconds 以秒为单位
* @return
*/
public static boolean expire(String key, long seconds) {
if (isNull(key))
return false;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.expire(key, seconds, TU_SECOND);
} catch (Exception e) {
log.error("====redis====expire key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 设置有效时间
* @param key
* @param date
* @return
*/
public static boolean expire(String key, Date date) {
if (isNull(key))
return false;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.expireAt(key, date);
} catch (Exception e) {
log.error("====redis====expire key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 获取有效时间
* @param key
* @return time 没有设置时间 、超时、 返回有效时间长度 <=0 标识
*/
public static long getExpire(String key) {
long time = -2;
if (isNull(key))
return time;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return time;
time = redisTemplate.getExpire(key, TU_SECOND);
} catch (Exception e) {
log.error("====redis====getExpire key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return time;
}
/**
* 查看key是否有效 即是否过期
* @param key
* @return
*/
public static boolean isValidKey(String key) {
long time = getExpire(key);
if (time == -2) { // -2 表示已经不存在了 -1 表示没有设置有效期即长期有效
return false;
}
return true;
}
//==================设置map类型的数据=============
/**
* 设置哈希值
*
* @param key
* @param field
* @param value
*/
public static boolean setMap(String key, String field, Object value) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForHash().put(key, field, value);
} catch (Exception e) {
log.error("====redis====setMap key[" + key + "] field[" + field + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return false;
} finally {
// ==== 把资源交还回连接池
}
return true;
}
/**
* 获取哈希值
*
* @param key
* @param field
* @return
*/
public static Object getMap(String key, String field) {
Object value = "";
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return value;
}
value = redisTemplate.opsForHash().get(key, field);//
} catch (Exception e) {
log.error("====redis====getMap key[" + key + "] field[" + field + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return value;
}
/**
* 删除哈希值
*
* @param key
* @param field
*/
public static boolean delMap(String key, Object... fields) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForHash().delete(key, fields);
} catch (Exception e) {
log.error("====redis====delMap key[" + key + "] field[" + fields + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 设置 map
* 一定要注意 这里是把map追加到原来的key中,不是替换,一定要注意
* @param <T>
* @param key
* @param value
*/
public static <T> boolean setMap(String key, Map<String, T> map) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForHash().putAll(key, map);
} catch (Exception e) {
log.error("====redis====setMap key[" + key + "] map[" + JsonUtils.toJson(map) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 获取 map
* @param <T>
* @param key
* @return list
*/
public static <T> Map<String, T> getMap(String key) {
Map<String, T> map = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return map;
}
BoundHashOperations<String, String, T> boundMap = redisTemplate.boundHashOps(key);
map = boundMap.entries();
} catch (Exception e) {
log.error("====redis====getMap key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return map;
}
//============list类型数据============
/**
* 设置队列值(顺序存储)
*
* @param key
* @param value
*/
public static boolean listLPush(String key, Object value) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForList().leftPush(key, value);
} catch (Exception e) {
log.error("====redis====listLPush key[" + key + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 设置队列值(反向存储)
*
* @param key
* @param value
*/
public static boolean listRPush(String key, Object value) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForList().rightPush(key, value);
} catch (Exception e) {
log.error("====redis====listRPush key[" + key + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 取出并获取列表中的第一个元素
*
* @param key
* @return
*/
public static Object listLPop(String key) {
Object value = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return value;
value = redisTemplate.opsForList().leftPop(key);
} catch (Exception e) {
log.error("====redis====listLPop key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return value;
}
/**
* 取出并获取列表中的第一个元素
*
* @param key
* @return
*/
public static Object listRPop(String key) {
Object value = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return value;
value = redisTemplate.opsForList().rightPop(key);
} catch (Exception e) {
log.error("====redis====listRPop key[" + key + "] error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return value;
}
/**
* 设置 list
* 一定要注意 这里是把list追加到原来的key中,不是替换,一定要注意
* @param <T>
* @param key
* @param value
*/
public static <T> boolean setList(String key, List<T> list) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForList().leftPushAll(key, list);
} catch (Exception e) {
log.error("====redis====setList key[" + key + "] list[" + JsonUtils.toJson(list) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 获取list
* @param <T>
* @param key
* @return list
*/
@SuppressWarnings("unchecked")
public static <T> List<T> getList(String key) {
List<T> list = null;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return list;
BoundListOperations<String, Object> boundList = redisTemplate.boundListOps(key);
if (boundList == null || boundList.size() <= 0)
return list;
list = (List<T>) boundList.range(0, boundList.size());
} catch (Exception e) {
log.error("====redis====getList key[" + key + "]error : [" + e.getMessage() + "]====");
} finally { // ==== 把资源交还回连接池
}
return list;
}
//============zset类型数据============
/**
* 添加数据到有序队列
* @param key key
* @param value 值
* @param score 对应的排序的值 根据score排序
* @return
*/
public static boolean zsetAdd(String key, Object value, double score) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForZSet().add(key, value, score);
} catch (Exception e) {
log.error("====redis====zsetAdd key[" + key + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 删除队列中的元素
* @param key
* @param values 可以是多个
* @return
*/
public static boolean zsetRemove(String key, Object... values) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForZSet().remove(key, values);
} catch (Exception e) {
log.error("====redis====zsetRemove key[" + key + "] value[" + JsonUtils.toJson(values) + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 根据score的值删除队列
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public static boolean zsetRemove(String key, double min, double max) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return false;
redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
} catch (Exception e) {
log.error("====redis====zsetRemove key[" + key + "] min[" + min + "] max[" + max + "] error : [" + e.getMessage() + "]====");
return false;
} finally { // ==== 把资源交还回连接池
}
return true;
}
/**
* 返回score的值
* @param key
* @param value
* @return 如果不存在 返回0
*/
public static double zsetScore(String key, Object value) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return 0;
return redisTemplate.opsForZSet().score(key, value);
} catch (Exception e) {
log.error("====redis====zsetScore key[" + key + "] value[" + JsonUtils.toJson(value) + "] error : [" + e.getMessage() + "]====");
return 0;
} finally { // ==== 把资源交还回连接池
}
}
/**
* 根据score的值范围 取数据
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public static Set<Object> zsetRange(String key, double min, double max) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return null;
return redisTemplate.opsForZSet().rangeByScore(key, min, max);
} catch (Exception e) {
log.error("====redis====zsetRange key[" + key + "] min[" + min + "] max[" + max + "] error : [" + e.getMessage() + "]====");
return null;
} finally { // ==== 把资源交还回连接池
}
}
/**
* 根据score的值范围 取数据
* 返回结果中会含有score
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public static Set<TypedTuple<Object>> zsetRangeWithsCore(String key, double min, double max) {
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate == null)
return null;
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
} catch (Exception e) {
log.error("====redis====zsetRangeWithsCore key[" + key + "] min[" + min + "] max[" + max + "] error : [" + e.getMessage() + "]====");
return null;
} finally { // ==== 把资源交还回连接池
}
}
//========================
/**
* 对某一个key进行加锁
* @param lockKey
* @return
*/
public static long lock(String key) {
if (isNull(key))
return 0;
long id = System.currentTimeMillis();
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate.opsForValue().setIfAbsent(key, id)) {
return id;
}
return 0;
} catch (Exception e) {
log.error("====redis====lock key[" + key + "] error : [" + e.getMessage() + "]====");
}
return 0;
}
/**
* 释放锁
* @param lockKey
* @param uuid
* @return
*/
public static boolean unLock(String key, long id) {
if (isNull(key) || isNull(id))
return false;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
if (redisTemplate.opsForValue().get(key).equals(id)) {
return redisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS);
}
return false;
} catch (Exception e) {
log.error("====redis====unLock key[" + key + "] error : [" + e.getMessage() + "]====");
}
return false;
}
/**
* 强制释放某个锁(慎用)
* @param key
*/
public static boolean forceUnLock(String key) {
if (isNull(key))
return false;
try {
RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
redisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS);
return true;
} catch (Exception e) {
log.error("====redis====unLock key[" + key + "] error : [" + e.getMessage() + "]====");
}
return false;
}
public static RedisTemplate<String, Object> getRedisTemplate() {
return JedisTemplate.getRedisTemplate();
}
}
redis工具类
最新推荐文章于 2018-11-21 16:15:13 发布