上篇我们聊了:如何查看redisson-spring-boot-starter和SpringBoot 对应版本
redisson介绍
Redisson是Redis Java客户端和实时数据平台。它提供了使用Redis更方便、更简单的方法。Redisson对象提供了一种关注点分离,使您能够专注于数据建模和应用程序逻辑。
redisson官网:Redisson: Easy Redis Java client and Real-Time Data Platform
redisson的GitHub地址:https://github.com/redisson/redisson
redisson wiki:https://github.com/redisson/redisson/wiki/1.-Overview
redis官网:https://redis.io
redis中文网:Redis中文网
redisson maven仓库地址: https://mvnrepository.com/artifact/org.redisson/redisson-spring-boot-starter
当前最新版本3.29.0,我们用的是3.26.0
SpringBoot 集成redisson
添加依赖
添加 redisson-spring-boot-starter
依赖即可。
<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.26.0</version>
</dependency>
redisson-spring-boot-starter的3.26.0对应spring-boot的3.2.0;
application.yml配置
spring:data:redis:# 数据库database: 0# 主机host: 127.0.0.1# 端口port: 6379# 密码password: 123456# 读超时timeout: 5s# 连接超时connect-timeout: 5s
外部引入redisson.yaml
与application.yml配置(二选一就行).
redisson配置文档地址:
spring:redis:redisson: file: classpath:redisson.yaml
RedissonClient
RedissonClient
RedissonRxClient
(响应式)RedissonReactiveClient
(响应式)RedisTemplate
ReactiveRedisTemplate
(响应式)
测试分布式锁代码
package com.chengxuyuanshitang.demo2;import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;@Slf4j
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationRedissonTests {// 注入 RedissonClient@AutowiredRedissonClient redissonClient;// 计数器AtomicInteger atomicCount = new AtomicInteger(0);@Testpublic void test() throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(50);for (int i = 0; i < 1000; i++) {new Thread(() -> {// 每个线程都创建自己的锁对象// 这是基于 Redis 实现的分布式锁RLock lock = this.redissonClient.getLock("redisTestLock");Boolean tryLock = Boolean.FALSE;try {// 上锁tryLock = lock.tryLock (30L, TimeUnit.SECONDS);if (tryLock) {log.info(" do something"+atomicCount.getAndAdd (1));}} catch (InterruptedException e) {log.error ("redis锁异常", e);} finally {// 释放锁lock.unlock ();}countDownLatch.countDown();}).start();}countDownLatch.await();log.info("count : [ {} ]", atomicCount.get ());}
}