java limit_简单的限流 java实现 RateLimiter

1. 基于QPS的限流 即单位时间的请求数不能超过一个阈值

package com.multiplyzero.mz.core.rpc;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

/**

*

* QpsRateLimiter

*

* @author xy.z@qq.com

*

* @since 2018年11月16日 上午10:09:12

*/

public class QpsRateLimiter {

private long lastTime;

private long interval;

private AtomicInteger remaind;

private int rate;

public QpsRateLimiter(int rate, long interval, TimeUnit unit) {

this.rate = rate;

this.interval = unit.toMillis(interval);

this.lastTime = System.currentTimeMillis();

this.remaind = new AtomicInteger(rate);

}

public boolean allowable() {

long now = System.currentTimeMillis();

if (now > lastTime + interval) {

remaind.set(rate);

lastTime = now;

}

int value = remaind.get();

boolean flag = false;

while (value > 0 && !flag) {

flag = remaind.compareAndSet(value, value - 1);

value = remaind.get();

}

return flag;

}

}

2.基于并发访问的限流 即并发数不能超过阈值 这个记得在finally中要release资源

package com.multiplyzero.mz.core.rpc;

import java.util.concurrent.Semaphore;

/**

*

* ExecuteRateLimiter

*

* @author xy.z@qq.com

*

* @since 2018年11月16日 上午10:11:23

*/

public class ExecuteRateLimiter {

private Semaphore rate;

public ExecuteRateLimiter(int rate) {

this.rate = new Semaphore(rate);

}

public boolean allowable() {

boolean allowable = rate.tryAcquire(1);

return allowable;

}

public void release() {

rate.release(1);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值