Table of Contents
前言使用步骤1. 引入库2. 配置 redis3. 增加配置4. 使用
在我们项目经常遇到并发问题,在单个项目中,使用自带的锁即可完成并发控制,在多个项目中,就需要使用分布式锁来解决。这里讲一下使用 Redis
来做分布式锁实现方案
在 Spring Boot 项目会根据 Spring Boot 依赖管理自动配置版本号
Maven
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在 application-xxx.yml
中配置
spring:
redis:
host: 127.0.0.1
port: 6379
timeout: 2500
password: xxxxx
RedisLockConfig.java
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
@Configuration
public class RedisLockConfig {
@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
return new RedisLockRegistry(redisConnectionFactory, "redis-lock",
TimeUnit.MINUTES.toMillis(10));
}
}
@Autowired
private RedisLockRegistry lockRegistry;
Lock lock = lockRegistry.obtain(key);
boolean locked = false;
try {
locked = lock.tryLock();
if (!locked) {
// 没有获取到锁的逻辑
}
// 获取锁的逻辑
} finally {
// 一定要解锁
if (locked) {
lock.unlock();
}
}