Redis常见用途

一、全局ID


    /** ID最大值 */
    final static long maxNum = 2100000000;
    /** 初始ID */
    final static long startNum = 1000000000;
    /** redis步长 */
    final static long redisStepLength = 1;

    /**
     * 获取redis主键序列号(10位长度)
     * 
     * @return
     * @throws RedisException
     */
    private long getAtomicLong(String key) throws RedisException {

        try {
            // 获取redis该key的值
            RAtomicLong seqLong = redissonClient.getAtomicLong(key);
            if (seqLong.get() > maxNum || seqLong.get() < startNum) {
                seqLong.set(startNum);
                seqLong.expire(1, TimeUnit.DAYS);
            }
            seqLong.addAndGet(redisStepLength);
            return seqLong.get();
        } catch (Exception e) {
            log.error("获取redis主键序列号异常: ", e);
            return RandomUtils.nextLong(startNum, maxNum);
        }
    }

    /**
     * 生成表主键ID流水号
     * 
     * @param key
     *            redisKEY,结构为param1:param2:param3....
     * @return 6+10=16位长度
     * @throws RedisException
     */
    public Long getSeq_16(String key) throws RedisException {

        checkForKey(key);
        String DateKEY = DateFormatUtils.format(new Date(), "yyMMdd");
        return Long.valueOf(DateKEY + getAtomicLong(key + ":" + DateKEY));
    }

二、分布锁

/**
     * when the time that thread execute business > leaseTime,it is not safe (maybe
     * others have already get the lock);
     * 
     * But we should not hold the lock all the time,setting leaseTime is necessary
     * 
     * 
     * @param key
     *            lockKey
     * @param waitTime
     *            最大等候锁时间
     * @param leaseTime
     *            过期自动释放锁时间
     * @param timeUnit
     *            时间单位
     * @throws RedisException
     *             throw when locked failed
     */
    public <T> T execute(String key, long waitTime, long leaseTime, TimeUnit timeUnit, LockCallback<T> callback)
            throws RedisException {

        checkForKey(key);

        RLock rLock = redissonClient.getLock(key);
        if (StringUtils.isBlank(key) || waitTime <= 0 || leaseTime <= 0 || timeUnit == null) {
            throw new RedisException(RedisErrorCode.KEY_LOCKED_FAILED);
        }
        boolean isLocked = false;
        try {
            // 尝试获取锁
            isLocked = rLock.tryLock(waitTime, leaseTime, timeUnit);

            if (!isLocked) {
                log.debug("locked failed ,key [{}]", key);
                throw new RedisException(RedisErrorCode.KEY_LOCKED_FAILED);
            }

            return callback.doWithLock();

        } catch (InterruptedException e) {
            log.debug("locked failed ,key [{}]: ", key, e);
            throw new RedisException(RedisErrorCode.KEY_LOCKED_FAILED);
        } finally {
            if (isLocked) {
                log.debug("Unlock {} ", key);
                rLock.unlock();
                log.debug("Unlock {} SUCCESS", key);
            }
        }
    }

调用分布锁锁的例子


    public static void main(String[] args) {

        RedisUtils redisUtils = new RedisUtils();
        String response;
        try {
            redisUtils.execute("lock:key:seq", 3000, 4000, TimeUnit.MILLISECONDS, new LockCallback<String>() {

                public String doWithLock() {

                    /*
                     * do business in Lock
                     */

                    return null;
                }

            });
        } catch (RedisException e) {

            /*
             * lock failed
             */
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值