Java限流——RateLimiter使用
阿新 • • 發佈:2019-01-31
令牌桶演算法:
在 Wikipedia 上,令牌桶演算法是這麼描述的:
- 每秒會有 r 個令牌放入桶中,或者說,每過 1/r 秒桶中增加一個令牌
- 桶中最多存放 b 個令牌,如果桶滿了,新放入的令牌會被丟棄
- 當一個 n 位元組的資料包到達時,消耗 n 個令牌,然後傳送該資料包
- 如果桶中可用令牌小於 n,則該資料包將被快取或丟棄
RateLimiter已經幫我們封裝好了,我們使用就行
jar引入
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency>
簡單程式碼(限流之快取):
import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PoolTest { private static RateLimiter rateLimiter; @Test public void pools(){ ExecutorService exxc = Executors.newFixedThreadPool(5); RateLimiter rateLimiter =RateLimiter.create(1); List<Runnable> tasks = new ArrayList<Runnable>(); for (int i = 0; i < 10; i++) { tasks.add(new UserRequest(i)); } for (Runnable runnable : tasks) { System.out.println("等待時間:" + rateLimiter.acquire()); exxc.execute(runnable); } } } class UserRequest implements Runnable { private int id; public UserRequest(int id) { this.id = id; } public void run() { System.out.println(id); } }