redisUtils

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;
    }

}


 

 


RedisUtils Lock是一个非常重要的工具,它提供了对Redis分布式锁的高效操作。 RedisUtils Lock的应用场景非常广泛,一般用于实现分布式环境下的资源互斥访问。在多线程、多进程、分布式系统中,为了避免数据竞争等问题,一般会采用锁等机制防止多个进程同时对同一资源进行操作。 RedisUtils Lock是基于Redis的SETNX指令实现的,它利用了Redis的原子性和单线程特性,拥有很高的性能和可靠性。在RedisUtils Lock的实现中,当一个线程占用了锁并且在使用资源时,其他线程是无法获取锁的,必须等待该线程释放锁后才能获取锁并执行相应的操作。 RedisUtils Lock的优点是: 1. 高效性:Redis是单线程的,因此使用RedisUtils Lock可以避免线程切换所带来的开销。 2. 可靠性:RedisUtils Lock采用的是SETNX指令实现的锁,具有很高的原子性和可靠性。 3. 易于使用:RedisUtils Lock封装了Redis的锁操作,使用起来非常方便。 4. 支持可重入:RedisUtils Lock支持可重入调用,在同一线程内多次加锁和释放锁。 RedisUtils Lock的缺点是: 1. 可能出现死锁:如果一个线程在加锁之后没有执行解锁操作,就会导致其他线程一直等待,从而出现死锁。 2. 不支持自旋锁:RedisUtils Lock采用的是阻塞锁,如果获取锁失败,则会一直阻塞等待。这种方式会占用线程资源,因此不适用于比较耗时的操作。 总之,RedisUtils Lock是一个非常实用的分布式锁工具,可以有效避免多线程、多进程、分布式系统中的资源竞争问题,具有很高的性能和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值