Guava单体项目限流方案
1、创建项目
maven配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
代码
/** * @description * @author: hq * @create: 2022-08-05 19:40 **/ @RestController @Slf4j public class TestController { // 每秒生产2个令牌 RateLimiter limiter = RateLimiter.create(2.0d); // 非阻塞限流 /** * 我请求的时候能否获取到我想要的令牌数量 * * @param count 令牌数量 * @return */ @GetMapping("/tryAcquire") public String tryAcquire(Integer count) { if (limiter.tryAcquire(count)) { log.info("success, rate is {}", limiter.getRate()); return "success"; } log.info("fail, rate is {}", limiter.getRate()); return "fail"; } /** * 在规定时间内我能否获取到想要的令牌数量 * * @param count 令牌数量 * @param timeout 超时时间 * @return */ @GetMapping("/tryAcquireWithTimeout") public String tryAcquireWithTimeout(Integer count, Integer timeout) { if (limiter.tryAcquire(count, timeout, TimeUnit.SECONDS)) { log.info("success, rate is {}", limiter.getRate()); return "success"; } log.info("fail, rate is {}", limiter.getRate()); return "fail"; } // 同步阻塞限流 @GetMapping("/acquire") public String acquire(Integer count) { limiter.acquire(count); log.info("success, rate is {}", limiter.getRate()); return "success"; } }