使用 Redisson 实现的 redis 分布式锁在 SpringBoot 中的简单使用

时间:2022-07-28
本文章向大家介绍使用 Redisson 实现的 redis 分布式锁在 SpringBoot 中的简单使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用 SpringBoot 2.3 创建一个web项目

1. 使用 redisson-spring-boot-starter 集成

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.13.4</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.70</version>
</dependency>

2. redisson 可以使用 SpringBoot 本身的redis配置, 也可以使用redisson的redis配置, 参考这里

我使用SpringBoot的redis的单机配置.

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
spring.redis.timeout=3s
spring.redis.ssl=false

3. 配置 RedisTemplage

@SpringBootConfiguration
public class RedisConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedissonConnectionFactory redissonConnectionFactory){
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(new GenericFastJsonRedisSerializer());
		redisTemplate.setConnectionFactory(redissonConnectionFactory);
		return redisTemplate;
	}
}

4. 配置 RedissonClient

@SpringBootConfiguration
public class RedissonConfig {
	
	@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("redis://127.0.0.1:6379");
		config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort);
		return Redisson.create(config);
	}
}

5. 分布式锁的基本使用

RLock lock = redissonClient.getLock("lock-1");
try {
	boolean tryLock = lock.tryLock(6, 5, TimeUnit.SECONDS);
	if(tryLock) {
		System.out.println("******************** Business ********************");
	}
} catch (InterruptedException e) {
	e.printStackTrace();
} finally {
	if(lock.isHeldByCurrentThread()) {   // 获取锁的线程才能解锁
		lock.unlock();
	} else {
		// 没有获得锁的处理
	}
}