分布式鎖的實現(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é)果

