Redis教程

redis 锁

本文主要是介绍redis 锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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;
        }
    }

 

这篇关于redis 锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!