前言
在上一篇,我们聊了下限流相关的概念和常用的限流解决方案,本篇我们先从最简单的限流组件Guawa开始
关于Guawa的介绍,我们上一篇有过简单的介绍,这里不再过多说明,直接从撸码开始吧
1、pom导入guawa依赖包
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
2、Guawa限流之阻塞式限流
我们以接口的方式进行说明,方便做测试看效果
@RestController
@Slf4j
public class RateLimitController {
/**
* 定义每秒钟发放2个令牌
*/
RateLimiter limiter = RateLimiter.create(2.0);
//非阻塞式限流
//http://localhost:8083/tryAcquire?count=1
//http://localhost:8083/tryAcquire?count=2
//http://localhost:8083/tryAcquire?count=4
@GetMapping("/tryAcquire")
public String tryAcquire(Integer count){
if(limiter.tryAcquire(count)){