一、引入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.23.5</version>
</dependency>
redison-spring-boot-starter依赖于与最新版本的spring-boot兼容的redison-spring数据模块。降级redison弹簧数据模块(如有必要),以支持以前的spring Boot版本:
redisson-spring-data module name | Spring Boot version |
---|---|
redisson-spring-data-16 | 1.3.y |
redisson-spring-data-17 | 1.4.y |
redisson-spring-data-18 | 1.5.y |
redisson-spring-data-2x | 2.x.y |
redisson-spring-data-3x | 3.x.y |
二、添加配置文件
使用 common Spring Boot 3.x+ settings:
spring:
data:
redis:
database:
host:
port:
password:
ssl:
timeout:
connectTimeout:
clientName:
cluster:
nodes:
sentinel:
master:
nodes:
使用common Spring Boot up to 2.7.x settings:
spring:
redis:
database:
host:
port:
password:
ssl:
timeout:
connectTimeout:
clientName:
cluster:
nodes:
sentinel:
master:
nodes:
配置redision属性( application.yaml**):**
spring:
redis:
redisson:
config: |
clusterServersConfig:
idleConnectionTimeout: 10000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
failedSlaveReconnectionInterval: 3000
failedSlaveCheckInterval: 60000
password: null
subscriptionsPerConnection: 5
clientName: null
loadBalancer: !<org.redisson.connection.balancer.RoundRobinLoadBalancer> {}
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
slaveConnectionMinimumIdleSize: 24
slaveConnectionPoolSize: 64
masterConnectionMinimumIdleSize: 24
masterConnectionPoolSize: 64
readMode: "SLAVE"
subscriptionMode: "SLAVE"
nodeAddresses:
- "redis://127.0.0.1:7004"
- "redis://127.0.0.1:7001"
- "redis://127.0.0.1:7000"
scanInterval: 1000
pingConnectionInterval: 0
keepAlive: false
tcpNoDelay: false
threads: 16
nettyThreads: 32
codec: !<org.redisson.codec.Kryo5Codec> {}
transportMode: "NIO"
三、使用 RedissonClient
一切就绪后,除了常用的 StringRedisTemplate
外,我们还可以注入如下由 Redisson 提供的 Bean:
RedissonClient
RedissonRxClient
(响应式)RedissonReactiveClient
(响应式)RedisTemplate
ReactiveRedisTemplate
(响应式)
四、接下来,我们使用 RedissonClient
来实现一个分布式锁,以进行测试:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import org.junit.jupiter.api.Test;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {
static final Logger logger = LoggerFactory.getLogger(DemoApplicationTests.class);
// 注入 RedissonClient
@Autowired
RedissonClient redissonClient;
// 计数器
private int count;
@Test
public void test() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1000);
for (int i = 0; i < 1000; i++) {
new Thread(() -> {
// 每个线程都创建自己的锁对象
// 这是基于 Redis 实现的分布式锁
Lock lock = this.redissonClient.getLock("counterLock");
try {
// 上锁
lock.lock();
// 计数器自增 1
this.count = this.count + 1;
} finally {
// 释放锁
lock.unlock();
}
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
logger.info("count = {}", this.count);
}
如上。我们在测试类中注入了 RedissonClient
Bean,并且定义了一个 count
属性。在测试方法中,启动 1000 个线程对 count
属性进行 +1
操作。其中,每个线程都通过 RedissonClient
获取分布式锁来控制对变量的并发修改。
运行测试,输出的日志如下:
INFO 4840 --- [ main] c.s.demo.test.DemoApplicationTests : count = 1000
如你所见,最后的结果是 1000,分布式锁生效。