序
本文主要研究一下redisson的rratelimiter
rratelimiter
redisson/src/main/java/org/redisson/api/rratelimiter.java
public interface rratelimiter extends rratelimiterasync, rexpirable { /** * initializes ratelimiter's state and stores config to redis server. * * @param mode - rate mode * @param rate - rate * @param rateinterval - rate time interval * @param rateintervalunit - rate time interval unit * @return {@code true} if rate was set and {@code false} * otherwise */ boolean trysetrate(ratetype mode, long rate, long rateinterval, rateintervalunit rateintervalunit); /** * updates ratelimiter's state and stores config to redis server. * * @param mode - rate mode * @param rate - rate * @param rateinterval - rate time interval * @param rateintervalunit - rate time interval unit */ void setrate(ratetype mode, long rate, long rateinterval, rateintervalunit rateintervalunit); /** * acquires a permit only if one is available at the * time of invocation. * * <p>acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>if no permit is available then this method will return * immediately with the value {@code false}. * * @return {@code true} if a permit was acquired and {@code false} * otherwise */ boolean tryacquire(); /** * acquires the given number of <code>permits</code> only if all are available at the * time of invocation. * * <p>acquires a permits, if all are available and returns immediately, * with the value {@code true}, * reducing the number of available permits by given number of permits. * * <p>if no permits are available then this method will return * immediately with the value {@code false}. * * @param permits the number of permits to acquire * @return {@code true} if a permit was acquired and {@code false} * otherwise */ boolean tryacquire(long permits); /** * acquires a permit from this ratelimiter, blocking until one is available. * * <p>acquires a permit, if one is available and returns immediately, * reducing the number of available permits by one. * */ void acquire(); /** * acquires a specified <code>permits</code> from this ratelimiter, * blocking until one is available. * * <p>acquires the given number of permits, if they are available * and returns immediately, reducing the number of available permits * by the given amount. * * @param permits the number of permits to acquire */ void acquire(long permits); /** * acquires a permit from this ratelimiter, if one becomes available * within the given waiting time. * * <p>acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>if no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * specified waiting time elapses. * * <p>if a permit is acquired then the value {@code true} is returned. * * <p>if the specified waiting time elapses then the value {@code false} * is returned. if the time is less than or equal to zero, the method * will not wait at all. * * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ boolean tryacquire(long timeout, timeunit unit); /** * acquires the given number of <code>permits</code> only if all are available * within the given waiting time. * * <p>acquires the given number of permits, if all are available and returns immediately, * with the value {@code true}, reducing the number of available permits by one. * * <p>if no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * the specified waiting time elapses. * * <p>if a permits is acquired then the value {@code true} is returned. * * <p>if the specified waiting time elapses then the value {@code false} * is returned. if the time is less than or equal to zero, the method * will not wait at all. * * @param permits amount * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ boolean tryacquire(long permits, long timeout, timeunit unit); /** * returns current configuration of this ratelimiter object. * * @return config object */ ratelimiterconfig getconfig(); /** * returns amount of available permits. * * @return number of permits */ long availablepermits(); }
rratelimiter继承了rratelimiterasync、rexpirable接口,它主要定义了trysetrate、setrate、tryacquire、acquire、getconfig、availablepermits方法
rratelimiterasync
redisson/src/main/java/org/redisson/api/rratelimiterasync.java
public interface rratelimiterasync extends rexpirableasync { /** * initializes ratelimiter's state and stores config to redis server. * * @param mode - rate mode * @param rate - rate * @param rateinterval - rate time interval * @param rateintervalunit - rate time interval unit * @return {@code true} if rate was set and {@code false} * otherwise */ rfuture<boolean> trysetrateasync(ratetype mode, long rate, long rateinterval, rateintervalunit rateintervalunit); /** * acquires a permit only if one is available at the * time of invocation. * * <p>acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>if no permit is available then this method will return * immediately with the value {@code false}. * * @return {@code true} if a permit was acquired and {@code false} * otherwise */ rfuture<boolean> tryacquireasync(); /** * acquires the given number of <code>permits</code> only if all are available at the * time of invocation. * * <p>acquires a permits, if all are available and returns immediately, * with the value {@code true}, * reducing the number of available permits by given number of permits. * * <p>if no permits are available then this method will return * immediately with the value {@code false}. * * @param permits the number of permits to acquire * @return {@code true} if a permit was acquired and {@code false} * otherwise */ rfuture<boolean> tryacquireasync(long permits); /** * acquires a permit from this ratelimiter, blocking until one is available. * * <p>acquires a permit, if one is available and returns immediately, * reducing the number of available permits by one. * * @return void */ rfuture<void> acquireasync(); /** * acquires a specified <code>permits</code> from this ratelimiter, * blocking until one is available. * * <p>acquires the given number of permits, if they are available * and returns immediately, reducing the number of available permits * by the given amount. * * @param permits the number of permits to acquire * @return void */ rfuture<void> acquireasync(long permits); /** * acquires a permit from this ratelimiter, if one becomes available * within the given waiting time. * * <p>acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>if no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * specified waiting time elapses. * * <p>if a permit is acquired then the value {@code true} is returned. * * <p>if the specified waiting time elapses then the value {@code false} * is returned. if the time is less than or equal to zero, the method * will not wait at all. * * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ rfuture<boolean> tryacquireasync(long timeout, timeunit unit); /** * acquires the given number of <code>permits</code> only if all are available * within the given waiting time. * * <p>acquires the given number of permits, if all are available and returns immediately, * with the value {@code true}, reducing the number of available permits by one. * * <p>if no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * the specified waiting time elapses. * * <p>if a permits is acquired then the value {@code true} is returned. * * <p>if the specified waiting time elapses then the value {@code false} * is returned. if the time is less than or equal to zero, the method * will not wait at all. * * @param permits amount * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ rfuture<boolean> tryacquireasync(long permits, long timeout, timeunit unit); /** * updates ratelimiter's state and stores config to redis server. * * * @param mode - rate mode * @param rate - rate * @param rateinterval - rate time interval * @param rateintervalunit - rate time interval unit * @return {@code true} if rate was set and {@code false} * otherwise */ rfuture<void> setrateasync(ratetype mode, long rate, long rateinterval, rateintervalunit rateintervalunit); /** * returns current configuration of this ratelimiter object. * * @return config object */ rfuture<ratelimiterconfig> getconfigasync(); /** * returns amount of available permits. * * @return number of permits */ rfuture<long> availablepermitsasync(); }
rratelimiterasync继承了rexpirableasync,它是async版本的rratelimiter,它主要定义了trysetrateasync、setrateasync、tryacquireasync、acquireasync、getconfigasync、availablepermitsasync方法
redissonratelimiter
redisson/src/main/java/org/redisson/redissonratelimiter.java
public class redissonratelimiter extends redissonexpirable implements rratelimiter { //...... @override public boolean tryacquire() { return tryacquire(1); } @override public rfuture<boolean> tryacquireasync() { return tryacquireasync(1l); } @override public boolean tryacquire(long permits) { return get(tryacquireasync(rediscommands.eval_null_boolean, permits)); } @override public rfuture<boolean> tryacquireasync(long permits) { return tryacquireasync(rediscommands.eval_null_boolean, permits); } @override public void acquire() { get(acquireasync()); } @override public rfuture<void> acquireasync() { return acquireasync(1); } @override public void acquire(long permits) { get(acquireasync(permits)); } @override public rfuture<void> acquireasync(long permits) { completionstage<void> f = tryacquireasync(permits, -1, null).thenapply(res -> null); return new completablefuturewrapper<>(f); } @override public boolean tryacquire(long timeout, timeunit unit) { return get(tryacquireasync(timeout, unit)); } @override public rfuture<boolean> tryacquireasync(long timeout, timeunit unit) { return tryacquireasync(1, timeout, unit); } @override public boolean tryacquire(long permits, long timeout, timeunit unit) { return get(tryacquireasync(permits, timeout, unit)); } }
redissonratelimiter继承了redissonexpirable,实现了rratelimiter接口
trysetrate
public boolean trysetrate(ratetype type, long rate, long rateinterval, rateintervalunit unit) { return get(trysetrateasync(type, rate, rateinterval, unit)); } public rfuture<boolean> trysetrateasync(ratetype type, long rate, long rateinterval, rateintervalunit unit) { return commandexecutor.evalwritenoretryasync(getrawname(), longcodec.instance, rediscommands.eval_boolean, "redis.call('hsetnx', keys[1], 'rate', argv[1]);" + "redis.call('hsetnx', keys[1], 'interval', argv[2]);" + "return redis.call('hsetnx', keys[1], 'type', argv[3]);", collections.singletonlist(getrawname()), rate, unit.tomillis(rateinterval), type.ordinal()); }
trysetrate委托给了trysetrateasync,这里主要是使用hsetnx来设置rate、interval、type三个值
setrate
public void setrate(ratetype type, long rate, long rateinterval, rateintervalunit unit) { get(setrateasync(type, rate, rateinterval, unit)); } public rfuture<void> setrateasync(ratetype type, long rate, long rateinterval, rateintervalunit unit) { return commandexecutor.evalwriteasync(getrawname(), longcodec.instance, rediscommands.eval_boolean, "local valuename = keys[2];" + "local permitsname = keys[4];" + "if argv[3] == '1' then " + " valuename = keys[3];" + " permitsname = keys[5];" + "end " +"redis.call('hset', keys[1], 'rate', argv[1]);" + "redis.call('hset', keys[1], 'interval', argv[2]);" + "redis.call('hset', keys[1], 'type', argv[3]);" + "redis.call('del', valuename, permitsname);", arrays.aslist(getrawname(), getvaluename(), getclientvaluename(), getpermitsname(), getclientpermitsname()), rate, unit.tomillis(rateinterval), type.ordinal()); }
setrate委托给了setrateasync,这里使用hset来写入rate、interval、type三个值,如果存在则覆盖;另外这里删除了valuename、permitsname这两个key
tryacquire
public boolean tryacquire(long permits) { return get(tryacquireasync(rediscommands.eval_null_boolean, permits)); } private <t> rfuture<t> tryacquireasync(rediscommand<t> command, long value) { byte[] random = getservicemanager().generateidarray(); return commandexecutor.evalwriteasync(getrawname(), longcodec.instance, command, "local rate = redis.call('hget', keys[1], 'rate');" + "local interval = redis.call('hget', keys[1], 'interval');" + "local type = redis.call('hget', keys[1], 'type');" + "assert(rate ~= false and interval ~= false and type ~= false, 'ratelimiter is not initialized')" + "local valuename = keys[2];" + "local permitsname = keys[4];" + "if type == '1' then " + "valuename = keys[3];" + "permitsname = keys[5];" + "end;" + "assert(tonumber(rate) >= tonumber(argv[1]), 'requested permits amount could not exceed defined rate'); " + "local currentvalue = redis.call('get', valuename); " + "local res;" + "if currentvalue ~= false then " + "local expiredvalues = redis.call('zrangebyscore', permitsname, 0, tonumber(argv[2]) - interval); " + "local released = 0; " + "for i, v in ipairs(expiredvalues) do " + "local random, permits = struct.unpack('bc0i', v);" + "released = released + permits;" + "end; " + "if released > 0 then " + "redis.call('zremrangebyscore', permitsname, 0, tonumber(argv[2]) - interval); " + "if tonumber(currentvalue) + released > tonumber(rate) then " + "currentvalue = tonumber(rate) - redis.call('zcard', permitsname); " + "else " + "currentvalue = tonumber(currentvalue) + released; " + "end; " + "redis.call('set', valuename, currentvalue);" + "end;" + "if tonumber(currentvalue) < tonumber(argv[1]) then " + "local firstvalue = redis.call('zrange', permitsname, 0, 0, 'withscores'); " + "res = 3 + interval - (tonumber(argv[2]) - tonumber(firstvalue[2]));" + "else " + "redis.call('zadd', permitsname, argv[2], struct.pack('bc0i', string.len(argv[3]), argv[3], argv[1])); " + "redis.call('decrby', valuename, argv[1]); " + "res = nil; " + "end; " + "else " + "redis.call('set', valuename, rate); " + "redis.call('zadd', permitsname, argv[2], struct.pack('bc0i', string.len(argv[3]), argv[3], argv[1])); " + "redis.call('decrby', valuename, argv[1]); " + "res = nil; " + "end;" + "local ttl = redis.call('pttl', keys[1]); " + "if ttl > 0 then " + "redis.call('pexpire', valuename, ttl); " + "redis.call('pexpire', permitsname, ttl); " + "end; " + "return res;", arrays.aslist(getrawname(), getvaluename(), getclientvaluename(), getpermitsname(), getclientpermitsname()), value, system.currenttimemillis(), random); }
tryacquire委托给了tryacquireasync,它通过一个lua脚本来执行,首先通过hget获取rate、interval、type的值,然后根据type来确定valuename、permitsname,如果type为0则valuename是getvaluename(),permitsname是getpermitsname(),如果type=1则valuename是getclientvaluename(),permitsname是getclientpermitsname();之后获取valuename的值,若为false则直接用设置rate、permits,并递减valuename;若为true则获取expiredvalues计算released值,再计算出currentvalue,若不够扣则计算返回值,若够扣则通过zadd添加当前permit(
system.currenttimemillis()
),然后递减valuename
acquire
public void acquire() { get(acquireasync()); } public rfuture<void> acquireasync() { return acquireasync(1); } public rfuture<void> acquireasync(long permits) { completionstage<void> f = tryacquireasync(permits, -1, null).thenapply(res -> null); return new completablefuturewrapper<>(f); } public rfuture<boolean> tryacquireasync(long permits, long timeout, timeunit unit) { long timeoutinmillis = -1; if (timeout >= 0) { timeoutinmillis = unit.tomillis(timeout); } completablefuture<boolean> f = tryacquireasync(permits, timeoutinmillis); return new completablefuturewrapper<>(f); } private completablefuture<boolean> tryacquireasync(long permits, long timeoutinmillis) { long s = system.currenttimemillis(); rfuture<long> future = tryacquireasync(rediscommands.eval_long, permits); return future.thencompose(delay -> { if (delay == null) { return completablefuture.completedfuture(true); } if (timeoutinmillis == -1) { completablefuture<boolean> f = new completablefuture<>(); getservicemanager().getgroup().schedule(() -> { completablefuture<boolean> r = tryacquireasync(permits, timeoutinmillis); commandexecutor.transfer(r, f); }, delay, timeunit.milliseconds); return f; } long el = system.currenttimemillis() - s; long remains = timeoutinmillis - el; if (remains <= 0) { return completablefuture.completedfuture(false); } completablefuture<boolean> f = new completablefuture<>(); if (remains < delay) { getservicemanager().getgroup().schedule(() -> { f.complete(false); }, remains, timeunit.milliseconds); } else { long start = system.currenttimemillis(); getservicemanager().getgroup().schedule(() -> { long elapsed = system.currenttimemillis() - start; if (remains <= elapsed) { f.complete(false); return; } completablefuture<boolean> r = tryacquireasync(permits, remains - elapsed); commandexecutor.transfer(r, f); }, delay, timeunit.milliseconds); } return f; }).tocompletablefuture(); }
acquire也是复用了tryacquireasync方法,只获取不到时会根据返回的delay进行重新调度,若timeoutinmillis不为-1则会根据超时时间进行计算和重新调度
availablepermits
public long availablepermits() { return get(availablepermitsasync()); } public rfuture<long> availablepermitsasync() { return commandexecutor.evalwriteasync(getrawname(), longcodec.instance, rediscommands.eval_long, "local rate = redis.call('hget', keys[1], 'rate');" + "local interval = redis.call('hget', keys[1], 'interval');" + "local type = redis.call('hget', keys[1], 'type');" + "assert(rate ~= false and interval ~= false and type ~= false, 'ratelimiter is not initialized')" + "local valuename = keys[2];" + "local permitsname = keys[4];" + "if type == '1' then " + "valuename = keys[3];" + "permitsname = keys[5];" + "end;" + "local currentvalue = redis.call('get', valuename); " + "if currentvalue == false then " + "redis.call('set', valuename, rate); " + "return rate; " + "else " + "local expiredvalues = redis.call('zrangebyscore', permitsname, 0, tonumber(argv[1]) - interval); " + "local released = 0; " + "for i, v in ipairs(expiredvalues) do " + "local random, permits = struct.unpack('bc0i', v);" + "released = released + permits;" + "end; " + "if released > 0 then " + "redis.call('zremrangebyscore', permitsname, 0, tonumber(argv[1]) - interval); " + "currentvalue = tonumber(currentvalue) + released; " + "redis.call('set', valuename, currentvalue);" + "end;" + "return currentvalue; " + "end;", arrays.aslist(getrawname(), getvaluename(), getclientvaluename(), getpermitsname(), getclientpermitsname()), system.currenttimemillis()); }
availablepermits委托给了availablepermitsasync,它执行lua脚本,先通过hget获取rate、interval、type的值,然后根据type来确定valuename、permitsname,如果type为0则valuename是getvaluename(),permitsname是getpermitsname(),如果type=1则valuename是getclientvaluename(),permitsname是getclientpermitsname();之后获取valuename对应的值currentvalue,若值为false则重新设置rate,否则通过expiredvalues重新计算released,若released大于0则更新到currentvalue,最后返回currentvalue
小结
redisson的rratelimiter提供了trysetrate、setrate、tryacquire、acquire、getconfig、availablepermits方法
- 其ratetype有overall(
值为0
)、per_client(值为1
)两个类型,如果type为0则valuename是getvaluename(),permitsname是getpermitsname(),如果type=1则valuename是getclientvaluename(),permitsname是getclientpermitsname() - 它主要定义了几个key,一个是getrawname,类型为hash,其key有rate、interval、type;一个是key为valuename,存储了当前的permits;一个是key为permitsname,类型是sorted set,其score为system.currenttimemillis(),value通过struct.pack了随机数长度、随机数、此次permit的value
- trysetrate委托给了trysetrateasync,这里主要是使用hsetnx来设置rate、interval、type三个值;setrate委托给了setrateasync,这里使用hset来写入rate、interval、type三个值,如果存在则覆盖;另外这里删除了valuename、permitsname这两个key
- tryacquire委托给了tryacquireasync,它通过一个lua脚本来执行,首先通过hget获取rate、interval、type的值,之后获取valuename的值,若为false则直接用设置rate、permits,并递减valuename;若为true则获取expiredvalues计算released值,再计算出currentvalue,若不够扣则计算返回值(告诉调用方可以延时多长时间再重试),若够扣则通过zadd添加当前permit(
system.currenttimemillis()
),然后递减valuename - acquire是也是复用了tryacquireasync方法,只获取不到时会根据返回的delay进行重新调度,若timeoutinmillis不为-1则会根据超时时间进行计算和重新调度
到此这篇关于redisson中rratelimiter分布式限流器的使用的文章就介绍到这了,更多相关redisson rratelimiter内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论