基于Guava RateLimiter实现限流

自闭症网瘾萝莉.ら 提交于 2020-05-08 12:24:27

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";
    }


}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!