分布式锁的实现方式有很多种方式,然而
spring
家族中已经有了比较优雅的实现
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默认情况下有16个分片,这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 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.测试
- 不加锁
可以看到返回的结果会出现不一致(预期应该是0)
- 加锁后
返回了正确的结果
网友评论