Guava RateLimiter 客户端限流 (单机版本)
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
import com.google.common.util.concurrent.RateLimiter; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.TimeUnit; /** * RateLimiter 只能存在单机项目 */ @RestController @Slf4j public class RateLimiterController { //每一秒2个令牌限流 RateLimiter limiter = RateLimiter.create(2.0); /** * 非阻塞限流 * * @param count 每秒消耗令牌 * @return */ @GetMapping("/tryAcquire") public String tryAcquire(Integer count) { if (limiter.tryAcquire(count)) { log.info("success,rate is {}", limiter.getRate()); return "success"; } else { 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"; } else { 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"; } }
来源:oschina
链接:https://my.oschina.net/u/4182459/blog/4270113