如果服务是单机,可以用JVM级别的锁syncronized,或者JUC中的锁,若服务是集群并发情况下保证并发安全就需要分布式锁。
1.利用redis的插件redisson
目录
1.1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.7</version>
</dependency>
1.2 添加配置yml文件中
spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
1.3 添加配置bean
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class RedisConfig {
private String potocol = "redis://";
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private String redisPort;
@Bean
public RedissonClient redissonClient(){
Config config = new Config();
config.useSingleServer().setAddress(potocol+redisHost+":"+redisPort).setDatabase(0);
return Redisson.create(config);
}
}
1.4 在类中使用
@Autowired
RedissonClient redissonClient;
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
//业务代码
lock.unlock();