使用SpringIntegration實現(xiàn)分布式鎖

分布式鎖的實現(xiàn)方式有很多種方式,然而spring家族中已經(jīng)有了比較優(yōu)雅的實現(xiàn)

1.引入依賴

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.integration</groupId>
      <artifactId>spring-integration-redis</artifactId>
    </dependency>

2.配置

spring:
  redis:
    host: localhost
    # 連接超時時間(記得添加單位,Duration)
    timeout: 10000ms
    # Redis默認(rèn)情況下有16個分片,這里配置具體使用的分片
    # database: 0
    lettuce:
      pool:
        # 連接池最大連接數(shù)(使用負(fù)值表示沒有限制) 默認(rèn) 8
        max-active: 8
        # 連接池最大阻塞等待時間(使用負(fù)值表示沒有限制) 默認(rèn) -1
        max-wait: -1ms
        # 連接池中的最大空閑連接 默認(rèn) 8
        max-idle: 8
        # 連接池中的最小空閑連接 默認(rèn) 0
        min-idle: 0

/**
 * @author haopeng
 * @date 2020-04-17 14:49
 */
@Configuration
public class RedisLockConfiguration {
    @Bean
    public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
        return new RedisLockRegistry(redisConnectionFactory, "distributed-lock", 5000L);
    }
}

3.編寫controller

    @GetMapping("/lock")
    public void lock() throws InterruptedException {
        Lock lock = redisLockRegistry.obtain("lock");
        stock = 1000;
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            pool.execute(() -> {
                try {
                    lock.tryLock(1,TimeUnit.SECONDS);
                    stock--;
                    lock.unlock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("stock= " + stock);
    }

4.測試

  • 不加鎖

可以看到返回的結(jié)果會出現(xiàn)不一致(預(yù)期應(yīng)該是0)


  • 加鎖后

返回了正確的結(jié)果


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容