package com.utils.redis;
import com.nonobank.app.log.LogUtils;
import comutils.SerializeUtil;
import comutils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.util.Pool;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* redis工具类
*
* @author liangjun
*/
@Component("redisUtil")
public class RedisUtil<T> {
private final long DEFAULT_LOCK_TIMEOUNT = 10000l;
@Autowired
private Pool<Jedis> redisPool;
public synchronized Jedis getJedis() {
Jedis jedis = null;
try {
jedis = redisPool.getResource();
} catch (Exception e) {
LogUtils.error("redisPool resource", e);
}
return jedis;
}
public String set(String key, String value) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.set(key, value);
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* @param key
* @param value
* @param expireTime seconds(int)
* @return
*/
public String set(String key, String value, int expireTime) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.setex(key, expireTime, value);
} finally {
if (jedis != null)
jedis.close();
}
}
public Long setnx(String key, String value) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.setnx(key, value);
} finally {
if (jedis != null)
jedis.close();
}
}
public Long expire(String key, int seconds) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.expire(key, seconds);
} finally {
if (jedis != null)
jedis.close();
}
}
public double incrByFloat(String key, double value) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.incrByFloat(key, value);
} finally {
if (jedis != null)
jedis.close();
}
}
public String get(String key) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.get(key);
} finally {
if (jedis != null)
jedis.close();
}
}
public Long del(final String... keys) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.del(keys);
} finally {
if (jedis != null)
jedis.close();
}
}
public Long del(String key) {
Jedis jedis = getJedis();
try {
return jedis == null ? null : jedis.del(key);
} finally {
if (jedis != null)
jedis.close();
}
}
/************************************************************************* 新加的 ******************************************************************************/
/**
* 失效时间-秒
*
* @param key
* @param map
* @param expireTime
*/
public boolean setMap(String key, Map<String, String> map, int expireTime) {
Jedis jedis = getJedis();
try {
String result = jedis.hmset(key, map);
if (StringUtils.isNotEmpty(result) && result.equalsIgnoreCase("OK")) {
jedis.expire(key, expireTime);
return true;
} else {
return false;
}
} finally {
jedis.close();
}
}
/**
* 获得结果 set
*
* @param key
*/
public String getMapKey(String key, String field) {
Jedis jedis = getJedis();
try {
String result = jedis.hget(key, field);
if (StringUtils.isNotEmpty(result) && result.equalsIgnoreCase("nil")) {
return null;
} else {
return result;
}
} finally {
jedis.close();
}
}
/**
* 获得结果 list
*
* @param key
*/
public List<String> getMapVal(String key, String field) {
Jedis jedis = getJedis();
try {
return jedis.hmget(key, field);
} finally {
jedis.close();
}
}
/**
* 获得结果 set
*
* @param key
*/
public Set<String> getMapKeys(String key) {
Jedis jedis = getJedis();
try {
return jedis.hkeys(key);
} finally {
jedis.close();
}
}
/**
* 获得结果 list
*
* @param key
*/
public List<String> getMapVals(String key) {
Jedis jedis = getJedis();
try {
return jedis.hvals(key);
} finally {
jedis.close();
}
}
/**
* 失效时间:一个小时
*
* @param key
* @param list
*/
public void setPushList(String key, List<String> list, int expireTime) {
Jedis jedis = getJedis();
try {
for (String str : list) {
jedis.lpush(key, str);
}
jedis.expire(key, expireTime);
} finally {
jedis.close();
}
}
/**
* 失效时间-秒
*
* @param key
* @param arrays
* @param expireTime
*/
public long setArrayList(String key, String[] arrays, int expireTime) {
Jedis jedis = getJedis();
try {
long rows = jedis.sadd(key, arrays);
if (rows == 1 || rows == 0) {
jedis.expire(key, expireTime);
}
return rows;
} finally {
jedis.close();
}
}
/**
* 获取整个列表值
*
* @param key
*/
public List<String> getList(String key) {
Jedis jedis = getJedis();
try {
return jedis.lrange(key, 0, -1);
} finally {
jedis.close();
}
}
public List<Object> pipelined(Map<String, String> datas) {
try (Jedis resource = getJedis();
Pipeline pipelined = resource.pipelined();) {
datas.forEach((k, v) -> {
pipelined.set(k, v);
});
List<Object> objects = pipelined.syncAndReturnAll();
return objects;
} catch (Exception e) {
}
return null;
}
/**
* 被存放的对象必须实现java.io.Serializable接口
* @param key
* @param obj
* @return
*/
/**
* 被存放的对象必须实现java.io.Serializable接口
*
* @param key
* @param obj
* @return
*/
public String setObject(String key, Object obj, int time) {
if (key != null && obj != null) {
Jedis jedis = getJedis();
if (jedis == null) {
return null;
}
// String s = jedis.set(key.getBytes(),SerializeUtil.serialize(obj));
String s = jedis.setex(key.getBytes(), time, SerializeUtil.serialize(obj));
if (jedis != null)
jedis.close();
return s;
}
return "NO";
}
public String setObject(String key, Object obj) {
if (key != null && obj != null) {
Jedis jedis = getJedis();
if (jedis == null) {
return null;
}
String s = jedis.set(key.getBytes(), SerializeUtil.serialize(obj));
if (jedis != null)
jedis.close();
return s;
}
return "NO";
}
public Object getObject(String key) {
Jedis jedis = getJedis();
try {
if (jedis == null)
return null;
byte[] objFormRedis = jedis.get(key.getBytes());
if (objFormRedis != null && objFormRedis.length > 0) {
Object obj = SerializeUtil.unserialize(objFormRedis);
return obj;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
return null;
}
public void ConstantForRedis(String key) {
Jedis jedis = getJedis();
if (jedis != null) {
jedis.del(key.getBytes());
}
}
public void delObject(String key) {
Jedis jedis = getJedis();
try {
jedis.del(key.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
}
public long increment(String key) {
Jedis jedis = getJedis();
long n = jedis.incr(key);
if (jedis != null)
jedis.close();
return n;
}
/**
* 存储 对象集合
* @param key
* @param objList
* @return
*/
public String setObjectList(String key, List<T> objList, int expireTime) {
String status = "No";
if (key != null && objList != null) {
Jedis jedis = getJedis();
if (jedis == null) {
return null;
}
try {
status = jedis.set(key.getBytes(), ObjectsTranscoder.serialize(objList));
jedis.expire(key, expireTime);
if (status != null && "OK".equalsIgnoreCase(status)) {
LogUtils.audit("将数据存入redis,key=" + key);
} else {
LogUtils.error("将券码数据存入redis出错,s=" + status);
}
} catch (Exception e) {
LogUtils.error("将券码数据存入redis出错,s=" + status);
} finally {
if (jedis != null)
jedis.close();
}
}
return status;
}
/**
* 根据key,获取对象集合
* @param key
* @return
*/
public List<T> getObjectList(String key) {
Jedis jedis = getJedis();
try {
if (jedis == null)
return null;
byte[] in = null;
in = jedis.get(key.getBytes());
if (in != null) {
List<T> resList = null;
resList = ObjectsTranscoder.deserialize(in);
LogUtils.audit("redis查询对象集合成功");
return resList;
}
} catch (Exception e) {
LogUtils.error("redis查询出现异常,key=" + key + "," + e);
} finally {
if (jedis != null)
jedis.close();
}
return null;
}
/**
* 获取锁
* @param lockKey
* @param lockValue
* @param mills 持有锁时间,单位毫秒
* @return
*/
public boolean lock(String lockKey,String lockValue,long mills){
boolean result=false;
try(Jedis resource = redisPool.getResource()){
String set = resource.set(lockKey, lockValue, "NX", "PX", mills);
result = "OK".equals(set);
}catch (Exception e){
LogUtils.error("--->>lock excption--->>key=" + lockKey, e);
}
LogUtils.audit("--->>lock result--->>key=" + lockKey+",result="+ result+",lockvalue="+lockValue);
return result;
}
/**
* 获取锁
* @param lockKey
* @param lockValue
* @return
*/
public boolean lock(String lockKey,String lockValue){
boolean result=false;
try(Jedis resource = redisPool.getResource()){
String set = resource.set(lockKey, lockValue, "NX", "PX", DEFAULT_LOCK_TIMEOUNT);
result = "OK".equals(set);
}catch (Exception e){
LogUtils.error("--->>lock excption--->>key=" + lockKey, e);
}
LogUtils.audit("--->>lock result--->>key=" + lockKey+",result="+ result+",lockvalue="+lockValue);
return result;
}
/**
* 释放锁
* @param lockKey
* @param lockValue
* @return
*/
public boolean unlock(String lockKey,String lockValue ){
boolean result=false;
String value=null;
try(Jedis resource = redisPool.getResource()){
value = resource.get(lockKey);
if(null==value){
result= true;
}else {
if (lockValue.equals(value)) {
result = resource.del(lockKey) > 0l;
} else {
result = true;
}
}
}catch (Exception e){
LogUtils.error("--->>unlock excption--->>key=" + lockKey, e);
}
LogUtils.audit("--->>unlock result--->>key=" + lockKey+",result="+result+",value="+value+",unluckValue="+lockValue);
return result;
}
}
<pre style="font-family: 宋体; font-size: 13.5pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">import java.math.BigDecimal;
import com.nonobank.app.system.dto.SystemMonthRateDescriptionDTO;
import com.nonobank.app.utils.constants.ConstantForMonthRate;
public class StringUtils {
public static boolean isEmpty(String str) {
return org.springframework.util.StringUtils.isEmpty(str);
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* 手机号取前3后4位 其他打*,如136****0055
*/
public static String buildMobileString(String mobile) {
String res = mobile.substring(0, 3) + "****" + mobile.substring(7, 11);
return res;
}
public static String getNullToDefaultValue(String value, String defaultValue) {
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
}
public static String mergeMonthDescription(SystemMonthRateDescriptionDTO dto) {
String resDescription = "";
String mergePattern = dto.getMergePattern();
if (mergePattern.equals(ConstantForMonthRate.MERGE_PATTERN1)) {
resDescription = dto.getBaseRate() + "%+" + dto.getMonthRate()
+ "%";
} else if (mergePattern.equals(ConstantForMonthRate.MERGE_PATTERN2)) {
resDescription = new BigDecimal(dto.getBaseRate())
.add(new BigDecimal(dto.getMonthRate())) + "%";
}
if (dto.getIsMergeSalaryRate()) {
resDescription += "+加薪" + dto.getSalaryRate() + "%";
}
return resDescription;
}
public static String getStringWithDefault(String value, String defaultStr) {
if (StringUtils.isEmpty(value)) {
return defaultStr;
} else {
return value;
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
}
return null;
}
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
}