1、引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.1-jre</version>
</dependency>
</dependencies>
2、ratelimiter实现,注意实际的使用是放在网关中的。
/**
- 功能说明:使用RateLimiter 实现令牌桶算法
*/
@RestController
public class IndexController {
@Autowired
private OrderService orderService;
// 解释:1.0 表示每秒中生成1个令牌存放在桶中
RateLimiter rateLimiter = RateLimiter.create(1.0);
// 下单请求
@RequestMapping(“/order”)
public String order() {
// 1.限流判断
// 如果在500秒内没有获取到令牌的话,则会一直等待
公众号:Java分享客栈
System.out.println(“生成令牌等待时间:” + rateLimiter.acquire());
boolean acquire = rateLimiter.tryAcquire(500, TimeUnit.MILLISECONDS);
if (!acquire) {
System.out.println(“先放弃
吧!”);
return “先放弃吧!”;
}
// 2.如果没有达到限流的要求,直接调用订单接口
boolean isOrderAdd = orderService.addOrder();
if (isOrderAdd) {
return “成功!”;
}
return “败!”;
}
}