目录
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.4</version>
</dependency>
<!--测试类依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--junit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
添加配置如下:
spring:
redis:
host: localhost
# password:
database: 8
jedis:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1
timeout: 2000
# # 集群
# cluster:
# nodes: ip:port,ip:port
二、基本测试
package com.dragonwu;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RBucket;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
/**
* @author DragonWu
* @date 2022-09-26 11:24
**/
@SpringBootTest(classes = RedissonApplication.class)
@RunWith(SpringRunner.class)
public class myTest {
@Autowired
private RedissonClient redissonClient;
@Test
//添加
public void testC() {
RBucket<String> name = redissonClient.getBucket("name");
name.set("Jack",10, TimeUnit.SECONDS);
}
@Test
//删除
public void testD() {
RSet<String> name = redissonClient.getSet("name");
name.delete();
}
}
三、分布式锁的实现
我们先了看一下使用Jedis实现分布式锁的思路,可以看到在一切考虑的比较完善的情况下,仍然存在一个问题,如果我们想对锁的时间进行周期性延长时,代码实现还是比较困难的,由此推出了Redisson框架,在此基础上已封装好了自动时间键值检索时间延迟机制。
Redisson实现原理图:
@Test
//分布式锁的实现案例
public void DistributedLock() {
//需要加锁对象的id
String lockKey = "product_001";
//1、获取该对象的锁
RLock lock = redissonClient.getLock(lockKey);
try {
//2、加锁
lock.lock(); //setnx key value timeunit底层,并且会周期性延迟生效时间
//3、锁里的操作
} catch (Exception e) {
e.printStackTrace();
} finally {
//4、释放锁
lock.unlock();
}
}
总结到此。
版权声明:本文为qq_50909707原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。