ichengzi / ichengzi.github.io

ichengzi's blogs and learn notes
https://ichengzi.github.io
1 stars 0 forks source link

redis分布式锁可能的坑 #38

Open ichengzi opened 3 years ago

ichengzi commented 3 years ago
        String key = "userid:10010";
        int lockSeconds = 5 * 60;

第一种写法

        Jedis jedis = new Jedis();
        Long flag = jedis.setnx(key, "write-lock");
        if (flag == 0) {
            System.out.println("lock fail");
            return;
        }
        // 如果这里程序崩溃, 回导致这个锁一直没法释放,然后导致程序异常
        jedis.expire(key, lockSeconds);
        //do business code

第二种写法

        SetParams params = new SetParams();
        params.nx();
        params.ex(lockSeconds);
        String code = jedis.set(key, "write-lock", params);
        if(!code.equals("OK")){
            System.out.println("lock fail");
            return;
        }
        //do business code

image