# 動態限速
> 內容來源于openresty討論組,點擊[這里](https://groups.google.com/forum/#!forum/openresty)
在我們的應用場景中,有大量的限制并發、下載傳輸速率這類要求。突發性的網絡峰值會對企業用戶的網絡環境帶來難以預計的網絡災難。
nginx示例配置:
~~~
location /download_internal/ {
internal;
send_timeout 10s;
limit_conn perserver 100;
limit_rate 0k;
chunked_transfer_encoding off;
default_type application/octet-stream;
alias ../download/;
}
~~~
我們從一開始,就想把速度值做成變量,但是發現limit_rate不接受變量。我們就臨時的修改配置文件限速值,然后給nginx信號做reload。只是沒想到這一臨時,我們就用了一年多。
直到剛剛,討論組有人問起網絡限速如何實現的問題,春哥給出了大家都喜歡的辦法:
> 地址:[https://groups.google.com/forum/#!topic/openresty/aespbrRvWOU](https://groups.google.com/forum/#!topic/openresty/aespbrRvWOU)
~~~
可以在 Lua 里面(比如 access_by_lua 里面)動態讀取當前的 URL 參數,然后設置 nginx 的內建變量$limit_rate(在 Lua 里訪問就是 ngx.var.limit_rate)。
http://nginx.org/en/docs/http/ngx_http_core_module.html#var_limit_rate
~~~
改良后的限速代碼:
~~~
location /download_internal/ {
internal;
send_timeout 10s;
access_by_lua 'ngx.var.limit_rate = "300K"';
chunked_transfer_encoding off;
default_type application/octet-stream;
alias ../download/;
}
~~~
經過測試,絕對達到要求。有了這個東東,我們就可以在lua上直接操作限速變量實時生效。再也不用之前笨拙的reload方式了。
PS: ngx.var.limit_rate 限速是基于請求的,如果相同終端發起兩個連接,那么終端的最大速度將是limit_rate的兩倍,原文如下:
~~~
Syntax: limit_rate rate;
Default:
limit_rate 0;
Context: http, server, location, if in location
Limits the rate of response transmission to a client. The rate is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit.
~~~
- 序
- Lua簡介
- Lua環境搭建
- 基礎數據類型
- 表達式
- 控制結構
- if/else
- while
- repeat
- 控制結構for的使用
- break,return
- Lua函數
- 函數的定義
- 函數的參數
- 函數的返回值
- 函數回調
- 模塊
- String庫
- Table庫
- 日期時間函數
- 數學庫函數
- 文件操作
- 元表
- 面向對象編程
- FFI
- LuaRestyRedisLibrary
- select+set_keepalive組合操作引起的數據讀寫錯誤
- redis接口的二次封裝(簡化建連、拆連等細節)
- redis接口的二次封裝(發布訂閱)
- pipeline壓縮請求數量
- script壓縮復雜請求
- LuaCjsonLibrary
- json解析的異常捕獲
- 稀疏數組
- 空table編碼為array還是object
- 跨平臺的庫選擇
- PostgresNginxModule
- 調用方式簡介
- 不支持事務
- 超時
- 健康監測
- SQL注入
- LuaNginxModule
- 執行階段概念
- 正確的記錄日志
- 熱裝載代碼
- 阻塞操作
- 緩存
- sleep
- 定時任務
- 禁止某些終端訪問
- 請求返回后繼續執行
- 調試
- 調用其他C函數動態庫
- 我的lua代碼需要調優么
- 變量的共享范圍
- 動態限速
- shared.dict 非隊列性質
- 如何添加自己的lua api
- 正確使用長鏈接
- 如何引用第三方resty庫
- 使用動態DNS來完成HTTP請求
- 緩存失效風暴
- Lua
- 下標從1開始
- 局部變量
- 判斷數組大小
- 非空判斷
- 正則表達式
- 不用標準庫
- 虛變量
- 函數在調用代碼前定義
- 抵制使用module()函數來定義Lua模塊
- 點號與冒號操作符的區別
- 測試
- 單元測試
- API測試
- 性能測試
- 持續集成
- 灰度發布
- web服務
- API的設計
- 數據合法性檢測
- 協議無痛升級
- 代碼規范
- 連接池
- c10k編程
- TIME_WAIT問題
- 與Docker使用的網絡瓶頸
- 火焰圖
- 什么時候使用
- 顯示的是什么
- 如何安裝火焰圖生成工具
- 如何定位問題