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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
| @Component @Slf4j public class TokenBucketRateLimiter implements RateLimiter { private final String name; private final Semaphore semaphore; private final int maxTokens; private final int refillTokens; private final long refillPeriod; private final ScheduledExecutorService scheduler; private final AtomicInteger currentTokens; private final AtomicLong lastRefillTime; public TokenBucketRateLimiter(String name, int maxTokens, int refillTokens, long refillPeriod) { this.name = name; this.maxTokens = maxTokens; this.refillTokens = refillTokens; this.refillPeriod = refillPeriod; this.semaphore = new Semaphore(maxTokens); this.currentTokens = new AtomicInteger(maxTokens); this.lastRefillTime = new AtomicLong(System.currentTimeMillis()); this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> { Thread thread = new Thread(r, "token-bucket-" + name); thread.setDaemon(true); return thread; }); startTokenRefillTask(); } @Override public boolean tryAcquire() { return tryAcquire(1); } @Override public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { return tryAcquire(1, timeout, unit); } @Override public void acquire() throws InterruptedException { acquire(1); } @Override public void release() { release(1); }
public boolean tryAcquire(int tokens) { if (tokens <= 0) { return true; } refillTokens(); if (currentTokens.get() >= tokens) { if (currentTokens.addAndGet(-tokens) >= 0) { try { semaphore.acquire(tokens); log.debug("获取令牌成功: limiter={}, tokens={}, available={}", name, tokens, getAvailablePermits()); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); currentTokens.addAndGet(tokens); return false; } } else { currentTokens.addAndGet(tokens); log.debug("令牌不足: limiter={}, required={}, available={}", name, tokens, currentTokens.get()); return false; } } return false; }
public boolean tryAcquire(int tokens, long timeout, TimeUnit unit) throws InterruptedException { if (tokens <= 0) { return true; } long startTime = System.currentTimeMillis(); long timeoutMillis = unit.toMillis(timeout); while (System.currentTimeMillis() - startTime < timeoutMillis) { if (tryAcquire(tokens)) { return true; } Thread.sleep(10); } return false; }
public void acquire(int tokens) throws InterruptedException { if (tokens <= 0) { return; } while (!tryAcquire(tokens)) { Thread.sleep(10); } }
public void release(int tokens) { if (tokens <= 0) { return; } semaphore.release(tokens); currentTokens.addAndGet(tokens); int current = currentTokens.get(); if (current > maxTokens) { currentTokens.set(maxTokens); } log.debug("释放令牌成功: limiter={}, tokens={}, available={}", name, tokens, getAvailablePermits()); } @Override public int getAvailablePermits() { return Math.min(currentTokens.get(), semaphore.availablePermits()); } @Override public String getName() { return name; }
private void startTokenRefillTask() { scheduler.scheduleAtFixedRate(() -> { try { refillTokens(); } catch (Exception e) { log.error("令牌补充任务异常: limiter={}", name, e); } }, refillPeriod, refillPeriod, TimeUnit.MILLISECONDS); }
private void refillTokens() { long currentTime = System.currentTimeMillis(); long timePassed = currentTime - lastRefillTime.get(); if (timePassed >= refillPeriod) { int tokensToAdd = (int) (timePassed / refillPeriod) * refillTokens; if (tokensToAdd > 0) { int current = currentTokens.get(); int newTokens = Math.min(current + tokensToAdd, maxTokens); if (currentTokens.compareAndSet(current, newTokens)) { lastRefillTime.set(currentTime); log.debug("补充令牌: limiter={}, added={}, total={}", name, tokensToAdd, newTokens); } } } }
public TokenBucketStatus getStatus() { TokenBucketStatus status = new TokenBucketStatus(); status.setName(name); status.setMaxTokens(maxTokens); status.setCurrentTokens(currentTokens.get()); status.setRefillTokens(refillTokens); status.setRefillPeriod(refillPeriod); status.setLastRefillTime(lastRefillTime.get()); return status; }
public void shutdown() { scheduler.shutdown(); try { if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) { scheduler.shutdownNow(); } } catch (InterruptedException e) { scheduler.shutdownNow(); Thread.currentThread().interrupt(); } } }
public class TokenBucketStatus { private String name; private int maxTokens; private int currentTokens; private int refillTokens; private long refillPeriod; private long lastRefillTime; }
|