Envoy实现.NET架构的网关(五)集成Redis实现限流
.NET網關與Gateway實戰-Envoy與kong課程
什么是限流
限流即限制并發量,限制某一段時間只有指定數量的請求進入后臺服務器,遇到流量高峰期或者流量突增時,把流量速率限制在系統所能接受的合理范圍之內,不至于讓系統被高流量擊垮。而Envoy可以通過envoy.filters.http.ratelimit插件實現限流。
限流服務
Envoy實現限流需要依賴限速服務,Envoy官方為我們提供了基于Redis和Memcached的限速服務 https://github.com/envoyproxy/ratelimit
?我們將其從github下載到本地,來看看其中的docker-compose.yaml的工作模式,我們注意到其中的example文件掛載目錄
?并且其中還制定了配置目錄是example/ratelimit
?我們來看看config.yaml和example.yaml的內容,發現其中定義了domain和描述符
?所以根據文檔的提示,我們在envoy配置中應該命中這些描述符才有效,下面我們通過docker-compose up啟動ratelimit服務,啟動之前我們需要調整docker-compose.yaml,需要將go mod代理指向國內的代理
?啟動ratelimit服務
配置Envoy
配置envoy之前我們需要注意一下幾點
需要用到envoy.filters.http.ratelimit過濾器
指定其domain為example.yaml中對應的rl
需要為其指定ratelimit服務的cluste
需要為route配置限速規則
具體配置如下
admin:address:socket_address:protocol: TCPaddress: 0.0.0.0port_value: 9902 static_resources:listeners:- name: listener_0address:socket_address:protocol: TCPaddress: 0.0.0.0port_value: 10000filter_chains:- filters:- name: envoy.filters.network.http_connection_managertyped_config:"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManagercodec_type: AUTOstat_prefix: ingresshttp_filters:- name: envoy.filters.http.ratelimittyped_config:"@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimitdomain: rlrequest_type: bothstage: 0rate_limited_as_resource_exhausted: truefailure_mode_deny: falseenable_x_ratelimit_headers: DRAFT_VERSION_03rate_limit_service:grpc_service:envoy_grpc:cluster_name: ratelimittransport_api_version: V3- name: envoy.filters.http.routertyped_config: {}route_config:name: routevirtual_hosts:- name: local_servicedomains: ["*"]routes:- match:prefix: "/"route:cluster: service_envoyproxy_iorate_limits:- actions:- request_headers:header_name: "foo"descriptor_key: "foo"clusters:- name: ratelimittype: STRICT_DNSconnect_timeout: 1slb_policy: ROUND_ROBINprotocol_selection: USE_CONFIGURED_PROTOCOLhttp2_protocol_options: {}load_assignment:cluster_name: ratelimitendpoints:- lb_endpoints:- endpoint:address:socket_address:address: 192.168.43.94port_value: 8081- name: service_envoyproxy_ioconnect_timeout: 30stype: strict_dns# Comment out the following line to test on v6 networks# dns_lookup_family: V4_ONLYlb_policy: ROUND_ROBINload_assignment:cluster_name: service_envoyproxy_ioendpoints:- lb_endpoints:- endpoint:address:socket_address:address: 192.168.43.94port_value: 5000啟動Envoy
docker run --rm -it -p 9902:9902 -p 10000:10000 -v D:/gateway/envoy/config/static/:/etc/envoy/ -v D:/gateway/envoy/logs:/logs envoyproxy/envoy-dev -c /etc/envoy/envoy-ratelimit.yaml測試限速
調用接口http://192.168.43.94:10000/Name,第三次的時候就會觸發429超限請求
?我們看看example/ratelimit/config/example.yaml,可以看到每分鐘只允許2次請求,至此限速驗證完成!!
系列文章:
Envoy實現.NET架構的網關(一)靜態配置與文件動態配置
Envoy實現.NET架構的網關(三)代理GRPC
Envoy實現.NET架構的網關(四)集成IdentityServer4實現OAuth2認證
總結
以上是生活随笔為你收集整理的Envoy实现.NET架构的网关(五)集成Redis实现限流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 双11,2分钟狂挣20亿的神秘大厂,急招
- 下一篇: 使用Hot Chocolate创建ASP