經常使用的限流算法有漏桶算法和令牌桶算法,guava的RateLimiter使用的是令牌桶算法,也就是以固定的頻率向桶中放入令牌,例如一秒鐘10枚令牌,實際業務在每次響應請求以前都從桶中獲取令牌,只有取到令牌的請求才會被成功響應,獲取的方式有兩種:阻塞等待令牌或者取不到當即返回失敗,下圖來自網上:git
本次實戰,咱們用的是guava的RateLimiter,場景是spring mvc在處理請求時候,從桶中申請令牌,申請到了就成功響應,申請不到時直接返回失敗;程序員
對於的源碼能夠在個人git下載,地址是:https://github.com/zq2599/blog_demos ,裏面有多個工程,本次實戰的工程爲guavalimitdemo,以下圖紅框所示:github
建立一個maven工程,在pom中把guava的依賴添加進來:算法
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>複製代碼
把限流服務封裝到一個類中AccessLimitService,提供tryAcquire()方法,用來嘗試獲取令牌,返回true表示獲取到,以下所示:spring
@Service
public class AccessLimitService {
//每秒只發出5個令牌
RateLimiter rateLimiter = RateLimiter.create(5.0);
/**
* 嘗試獲取令牌
* @return
*/
public boolean tryAcquire(){
return rateLimiter.tryAcquire();
}
}複製代碼
調用方是個普通的controller,每次收到請求的時候都嘗試去獲取令牌,獲取成功和失敗打印不一樣的信息,以下:tomcat
@Controller
public class HelloController {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private AccessLimitService accessLimitService;
@RequestMapping("/access")
@ResponseBody
public String access(){
//嘗試獲取令牌
if(accessLimitService.tryAcquire()){
//模擬業務執行500毫秒
try {
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
return "aceess success [" + sdf.format(new Date()) + "]";
}else{
return "aceess limit [" + sdf.format(new Date()) + "]";
}
}
}複製代碼
以上就是服務端的代碼了,打包部署在tomcat上便可,接下來咱們寫一個類,十個線程併發訪問上面寫的controller:併發
public class AccessClient {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
/**
* get請求
* @param realUrl
* @return
*/
public static String sendGet(URL realUrl) {
String result = "";
BufferedReader in = null;
try {
// 打開和URL之間的鏈接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 創建實際的鏈接
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public void access() throws Exception{
final URL url = new URL("http://localhost:8080/guavalimitdemo/access");
for(int i=0;i<10;i++) {
fixedThreadPool.submit(new Runnable() {
public void run() {
System.out.println(sendGet(url));
}
});
}
fixedThreadPool.shutdown();
fixedThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
public static void main(String[] args) throws Exception{
AccessClient accessClient = new AccessClient();
accessClient.access();
}
}
複製代碼
直接執行AccessClient的main方法,能夠看到結果以下:mvc
部分請求因爲獲取的令牌能夠成功執行,其他請求沒有拿到令牌,咱們能夠根據實際業務來作區分處理。還有一點要注意,咱們經過RateLimiter.create(5.0)配置的是每一秒5枚令牌,可是限流的時候發出的是6枚,改用其餘值驗證,也是實際的比配置的大1。app
以上就是快速實現限流的實戰過程,此處僅是單進程服務的限流,而實際的分佈式服務中會考慮更多因素,會複雜不少。maven