博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
redisUtils
阅读量:4299 次
发布时间:2019-05-27

本文共 12796 字,大约阅读时间需要 42 分钟。

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
{ private final long DEFAULT_LOCK_TIMEOUNT = 10000l; @Autowired private Pool
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
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
getMapVal(String key, String field) { Jedis jedis = getJedis(); try { return jedis.hmget(key, field); } finally { jedis.close(); } } /** * 获得结果 set * * @param key */ public Set
getMapKeys(String key) { Jedis jedis = getJedis(); try { return jedis.hkeys(key); } finally { jedis.close(); } } /** * 获得结果 list * * @param key */ public List
getMapVals(String key) { Jedis jedis = getJedis(); try { return jedis.hvals(key); } finally { jedis.close(); } } /** * 失效时间:一个小时 * * @param key * @param list */ public void setPushList(String key, List
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
getList(String key) { Jedis jedis = getJedis(); try { return jedis.lrange(key, 0, -1); } finally { jedis.close(); } } public List
pipelined(Map
datas) { try (Jedis resource = getJedis(); Pipeline pipelined = resource.pipelined();) { datas.forEach((k, v) -> { pipelined.set(k, v); }); List
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
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
getObjectList(String key) { Jedis jedis = getJedis(); try { if (jedis == null) return null; byte[] in = null; in = jedis.get(key.getBytes()); if (in != null) { List
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; }}
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;    }}
 
 

转载地址:http://pmpws.baihongyu.com/

你可能感兴趣的文章
Docker基础-16-网络-Linux网络命名空间
查看>>
Docker基础-17-网络-两个容器为什么能通信
查看>>
Docker基础-18-网络-两个网络命名空间网络通信配置过程
查看>>
Docker基础-19-网络-bridge模式和docker0详解
查看>>
Docker基础-20-网络-容器link关系和新建bridge网络
查看>>
Docker基础-21-网络-none和host网络
查看>>
Docker基础-22-volume-数据持久化之data volume
查看>>
Docker基础-23-数据-数据持久化之Bind Mouting
查看>>
Java数据结构和算法-1-数组-自定义封装一个数组操作类(1)
查看>>
Java数据结构和算法-2-数组-自定义封装一个数组操作类(2)
查看>>
Java数据结构和算法-3-数组-简单排序:冒泡排序/选择排序/插入排序
查看>>
Java数据结构和算法-4-栈和队列-封装一个自定义栈和队列类并提供相关类方法
查看>>
Java数据结构和算法-5-单链表方法
查看>>
Jenkins高级篇之Pipeline技巧篇-1-小白搭建Pipeline项目开发环境
查看>>
Jenkins高级篇之Pipeline技巧篇-2-如何处理多个参数化变量
查看>>
Jenkins高级篇之Pipeline技巧篇-3-JSON文件处理多个参数进一步优化
查看>>
Jenkins高级篇之Pipeline技巧篇-4-根据参数传入条件控制执行不同stage
查看>>
Jenkins高级篇之Pipeline技巧篇-5-pipeline中如何代码串联多个job的执行
查看>>
Jenkins高级篇之Pipeline技巧篇-6-pipeline中使用jenkins share lib 方法
查看>>
JavaWeb学习-JDBC系列-1-JDBC概述
查看>>