ratelimit實現envoy全侷限速

envoy rate limit介紹

envoy中有以下限速方式:

  • 全侷限速

Envoy的全局請求限速服務器,檢查是否接受。
全局意味著所有代理都將使用一個計數器作為評估請求的基礎。
每個代理都請求一個上游速率限制服務(在此示例中為Lyfts),該服務將在envoy外部運行以決定請求。

  • 本地限速

本地速率限制計數器在處理請求的單個envoy代理的上下文中運行。這意味著每個代理都跟蹤其管理的連接並應用限速策略(即熔斷)
最新的版本添加了一個使用自身令牌桶進行本地限速功能(pr 9354)

環境準備

安裝envoy

<code>brew tap tetratelabs/getenvoy
brew install getenvoy
/<code>

啟動redis

<code>docker run -p 6379:6379 redis
/<code>

啟動上游服務

<code>python -m SimpleHTTPServer 1234 

/<code>

使用lyft/ratelimit進行限速

啟動ratelimit

<code>export USE_STATSD=false 
export LOG_LEVEL=debug
export REDIS_SOCKET_TYPE=tcp
export REDIS_URL=localhost:6379
export RUNTIME_ROOT="./"
export RUNTIME_SUBDIRECTORY=ratelimit
git clone https://github.com/lyft/ratelimit.git
cat >> config.yaml < EOF
domain: ratelimiter
descriptors:
- key: header_match
value: lyft-rate-limit
rate_limit:
unit: minute
requests_per_unit: 2
EOF
cd ratelimit
go get -v github.com/Masterminds/glide
glide install
go run src/service_cmd/main.go
/<code>

啟動envoy

<code>cat >> config.yaml < EOF
admin:
access_log_path: /tmp/admin_access.log
address:
socket_address: { address: 127.0.0.1, port_value: 9901 }
static_resources:
listeners:
- name: listener_0
address:
socket_address: { address: 127.0.0.1, port_value: 10000 }
filter_chains:
- filters:
- name: envoy.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.config.filter.network.http_connection_manager.v2.HttpConnectionManager
stat_prefix: ingress_http
codec_type: AUTO
route_config:
name: local_route

virtual_hosts:
- name: local_service
domains: ["ratelimiter"]
routes:
- match: { prefix: "/" }
route: { cluster: some_service }
rate_limits:
- actions:
- header_value_match:
descriptor_value: lyft-rate-limit
expect_match: false
headers:
- name: ":path"
exact_match: "/"
stage: 0
http_filters:
- name: envoy.rate_limit
config:
stage: 0
domain: "ratelimiter"
request_type: external
failure_mode_deny: true
rate_limit_service:
grpc_service:
envoy_grpc:
cluster_name: rate_limit_service
- name: envoy.local_rate_limit
config:
token_bucket:
max_tokens: 10
fill_interval: 1s
- name: envoy.router
clusters:
- name: some_service
connect_timeout: 0.25s
type: STATIC
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: some_service
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: 127.0.0.1
port_value: 1234
- name: rate_limit_service
connect_timeout: 0.25s
type: static
lb_policy: round_robin

http2_protocol_options: {}
hosts:
- socket_address:
address: 127.0.0.1
port_value: 8081
EOF
envoy -c config.yaml
/<code>

驗證

前兩次正常,第三次發現返回429,限速正常

<code>$ curl -I -H 'HOST: ratelimiter' 127.0.0.1:10000
HTTP/1.1 429 Too Many Requests
x-envoy-ratelimited: true
date: Tue, 14 Jan 2020 07:14:35 GMT
server: envoy
transfer-encoding: chunked
/<code>


分享到:


相關文章: