redis 锁

2024-10-09 08:08:28 浏览数 (3)

代码语言:javascript复制
demo1
public ErrorCode initDemo1(@RequestParam("orderNo") String orderNo) throws IOException {
        String lockKey = KEY   orderNo;
        Boolean hasKey = null;
        try {
            //锁判断
            hasKey = redisTemplate.hasKey(lockKey);
            
            int index = 0;
            while (hasKey && index < 3) {
                log.info(">>>>>>>>>>>>>刷新,wait>>>>>>>>>>>>>");
                index  ;
                Thread.sleep(1500L * index);
                hasKey = redisTemplate.hasKey(lockKey);
            }
            if (index > 0) {
                log.info(">>>>>>>>>>>>>wait index:{} hasKey: {}", index, hasKey);
            }
            
            //加锁
            redisTemplate.opsForValue().set(lockKey, "1", 5, TimeUnit.SECONDS);
            
            //业务操作-刷新es todo 业务逻辑

            //去锁
            redisTemplate.delete(lockKey);
            return ErrorCode.SUCCESS;
        } catch (Exception e) {
            //去锁
            redisTemplate.delete(lockKey);
            return ErrorCode.SYS_ERROR;
        } 
    }
    

demo2    
public ErrorCode initDemo2(@RequestParam("orderNo") String orderNo) throws IOException {
        String lockKey = KEY   orderNo;
        Boolean hasKey = null;
        try {
            hasKey = lock(lockKey, orderNo, 5);
            if(hasKey != null && hasKey) {
                //业务操作-刷新es todo 业务逻辑
            }else {
                return ErrorCode.LOCK_FAILED;
            }
            return ErrorCode.SUCCESS;
        } catch (Exception e) {
            return ErrorCode.SYS_ERROR;
        } finally{
            if(hasKey != null && hasKey) {
                redisTemplate.delete(lockKey);
            }
        }
    }
    
    
    public boolean lock(String key, String value, long releaseTime) {
        // 尝试获取锁  spring-data-redis 2.1版本以上     //implementation group: 'org.springframework.data', name: 'spring-data-redis', version: '2.1.0.RELEASE'
//         Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS); //.setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
         // 判断结果
//         return boo != null && boo;
        
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.multi();
        redisTemplate.opsForValue().setIfAbsent(key,value);
        redisTemplate.expire(key,releaseTime, TimeUnit.SECONDS);
        List result = redisTemplate.exec(); // 这里result会返回事务内每一个操作的结果,如果setIfAbsent操作失败后,result[0]会为false。
        if(result != null && true == (Boolean)result.get(0)){
            return true;
        }else {
            return false;
        }
    }

0 人点赞