引言 年前有个需求,批量请求供应商API,要有限流操作,并支持TPS与并发数可配置,那时候简单的查了查资料,任务结束就过去了,最近又有个限流的小需求,所以又翻出了以前的代码。
本次简单记录一下令牌桶的实现:
令牌桶算法的原理是系统会以一个恒定的速度往桶里放入令牌,而如果请求需要被处理,则需要先从桶里获取一个令牌,当桶里没有令牌可取时,则拒绝服务。
实现思路: 用LinkedBlockingQueue作为装令牌的桶,Executors.newSingleThreadScheduledExecutor()作为定时器定时将令牌放入桶中,使用构建者模式的代码风格。忘了以前在哪抄的了,就这样吧。
贴上核心代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class TokenBucket { private int maxFlowRate; private int avgFlowRate; private LinkedBlockingQueue<Byte> tokenQueue; private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); private volatile Object mutexDoNotUseDirectly = new Object (); private volatile boolean isStart = false ; private static final Byte A_CHAR = 'a' ; private TokenBucket () { } public static TokenBucket newBuilder () { return new TokenBucket (); } public TokenBucket maxFlowRate (int maxFlowRate) { this .maxFlowRate = maxFlowRate; return this ; } public TokenBucket avgFlowRate (int avgFlowRate) { this .avgFlowRate = avgFlowRate; return this ; } public TokenBucket build () { init(); return this ; } private void init () { if (maxFlowRate > 0 ) { tokenQueue = new LinkedBlockingQueue <>(maxFlowRate); } TokenProducer tokenProducer = new TokenProducer (avgFlowRate, this ); scheduledExecutorService.scheduleAtFixedRate(tokenProducer, 0 , 1 , TimeUnit.SECONDS); isStart = true ; } public void stop () { isStart = false ; scheduledExecutorService.shutdown(); } public boolean isStarted () { return isStart; } private void addTokens (Integer tokenNum) { for (int i = 0 ; i < tokenNum; i++) { tokenQueue.offer(A_CHAR); } } public boolean tryAcquire () { synchronized (mutexDoNotUseDirectly) { if (tokenQueue.size() > 0 ) { Byte poll = tokenQueue.poll(); if (poll != null ) { return true ; } } } return false ; } private class TokenProducer implements Runnable { private int tokenNum; private TokenBucket tokenBucket; private TokenProducer (int tokenNum, TokenBucket tokenBucket) { this .tokenNum = tokenNum; this .tokenBucket = tokenBucket; } @Override public void run () { tokenBucket.addTokens(tokenNum); } } }