ホームページ  >  記事  >  データベース  >  SpringBoot で Redis をグローバル ロックとして使用する方法

SpringBoot で Redis をグローバル ロックとして使用する方法

PHPz
PHPz転載
2023-05-29 19:13:041492ブラウズ

1. ロックなしでリソース競合をシミュレートします

public class CommonConsumerService {
    //库存个数
    static int goodsCount = 900;
    //卖出个数
    static int saleCount = 0;
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {Thread.sleep(2);} catch (InterruptedException e) {}
                if (goodsCount > 0) {
                    goodsCount--;
                    System.out.println("剩余库存:" + goodsCount + " 卖出个数" + ++saleCount);
                }
            }).start();
        }
        Thread.sleep(3000);
    }
}

一度実行してください。最後の数行の出力結果は次のとおりです。何か問題が発生したことは明らかです。販売済みの製品は 899 個のみです。残り0商品、これは非常に奇妙なことですが、どうやら一部の商品が某スレッドに流用されたようです。

....
残り在庫: 5 個売れました 893
残り在庫: 5 個売れました 894
残り在庫: 4 個売れました 895
残り在庫: 2 個販売個数: 896
残り在庫: 2 販売個数: 897
残り在庫: 1 販売個数: 898
残り在庫: 0 販売個数: 899

2. redis を使用してロックする

redis はシングルスレッドでシリアルに実行され、redis を使用してリソースをロックします。

1. まず依存関係を導入します

compile "org.springframework.boot:spring-boot-starter-data-redis"

2. Redis ロック ツール クラスを導入します

package com.kingboy.common.utils;
import redis.clients.jedis.Jedis;
import java.util.Collections;
/**
 * @author kingboy--KingBoyWorld@163.com
 * @date 2017/12/29 下午1:57
 * @desc Redis工具.
 */
public class RedisTool {
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;
    /**
     * 尝试获取分布式锁
     * @param jedis      Redis客户端
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
    /**
     * 释放分布式锁
     * @param jedis     Redis客户端
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
        String script = "if redis.call(&#39;get&#39;, KEYS[1]) == ARGV[1] then return redis.call(&#39;del&#39;, KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
}

3. ロックなしで上記のサンプル コードを次のように変更します:

public class RedisLockConsumerService {
    //库存个数
    static int goodsCount = 900;
    //卖出个数
    static int saleCount = 0;
    @SneakyThrows
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "192.168.0.130", 6379, 1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {Thread.sleep(2);} catch (InterruptedException e) {}
                Jedis jedis = jedisPool.getResource();
                boolean lock = false;
                while (!lock) {
                    lock = RedisTool.tryGetDistributedLock(jedis, "goodsCount", Thread.currentThread().getName(), 10);
                }
                if (lock) {
                    if (goodsCount > 0) {
                        goodsCount--;
                        System.out.println("剩余库存:" + goodsCount + " 卖出个数" + ++saleCount);
                    }
                }
                RedisTool.releaseDistributedLock(jedis, "goodsCount", Thread.currentThread().getName());
                jedis.close();
            }).start();
        }
        Thread.sleep(3000);
        jedisPool.close();
    }
}

プログラムを数回実行すると、出力結果は以下のようになり、結果が正しいことがわかります。

....
残り在庫: 6 個売れました 894
残り在庫: 5 個売れました 895
残り在庫: 4 個売れました 896
残り在庫: 3 個売れました売れました 897
残り在庫: 2 個売れました 898
残り在庫: 1 個売れました 899
残り在庫: 0 個売れました 900

以上がSpringBoot で Redis をグローバル ロックとして使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。