1.引入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId> <!-- 实现对 Caches 的自动化配置 -->
</dependency>
2.配置文件
spring:
# Cache 配置项
cache:
type: REDIS
redis:
time-to-live: 1h # 设置过期时间为 1 小时
key-prefix: ${spring.application.name}
# Redis 配置。Redisson 默认的配置足够使用,一般不需要进行调优
redis:
host: 111.111.111.111 # 地址
port: 6379 # 端口
database: 7 # 数据库索引
password: 111111 # 密码
3.redisson锁
int n = 500;
@GetMapping("/redisson")
@Operation(summary = "redisson")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
public R<String> redisson(@RequestParam("id") Long id) throws InterruptedException {
String desc = "";
String key = "stockLock";
RLock lock = redissonClient.getFairLock(key);
try {
//第一个参数,尝试获取锁的时间,锁执行时间
boolean b = lock.tryLock(1000,30000,TimeUnit.MILLISECONDS);
if (b) {
log.info("尝试获取锁:" + Thread.currentThread().getName());
Thread.sleep(5000);
log.info("获取到锁true:" + Thread.currentThread().getName() + " 剩余数量:" + (--n));
desc = "获取到锁true";
} else {
log.info("获取到锁false" + Thread.currentThread().getName());
desc = "获取到锁false";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(lock.isHeldByCurrentThread()){
log.info("准备释放锁:" + Thread.currentThread().getName() );
lock.unlock();
}
}
return success(desc);
}
4.lock4j实现分布式锁
用法很简单,看官方文档即可
简单使用
@Lock4j
@Lock4j(keys = {"#id","#name"}, expire = 3000, acquireTimeout = 1000)
@GetMapping("/lock4j")
@Operation(summary = "lock4j")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@Lock4j
public CommonResult<String> lock4j(@RequestParam("id") Long id) throws InterruptedException {
String uuid = UUID.randomUUID().toString();
log.info("尝试获取锁:" + Thread.currentThread().getName() + " uuid:" + uuid);
Thread.sleep(5000);
log.info("获取到锁true:" + Thread.currentThread().getName() + " uuid:" + uuid);
return success("获取到锁true");
}
官方文档:
lock4j: 基于Spring AOP 的声明式和编程式分布式锁,支持RedisTemplate、Redisson、Zookeeper - Gitee.com
5.ratelimiter实现接口限流
用法很简单,看官方文档即可
1.引入依赖
<dependency>
<groupId>com.github.taptap</groupId>
<artifactId>ratelimiter-spring-boot-starter</artifactId>
<version>1.3</version>
</dependency>
配置:
spring.ratelimiter.enabled=true
spring.ratelimiter.redis-address=redis://127.0.0.1:6379
spring.ratelimiter.redis-password=xxx
2.简单使用
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/get")
@RateLimit(rate = 5, rateInterval = "10s")
public String get(String name) {
return "hello";
}
}
官方文档:
GitHub - taptap/ratelimiter-spring-boot-starter: 基于 redis 的偏业务应用的分布式限流组件,使得项目拥有分布式限流能力变得很简单。

591

被折叠的 条评论
为什么被折叠?



