KONG根据请求参数限流
背景
价格接口 /search 同时支持缓存查价和实时查价,主要通过searchType字段区分这两种请求。
- searchType 为空时为缓存查价,QPS很高。
- searchType 不为空时为实时查价,但QPS远低于普通查价。
如果直接对该接口限流,当流量波动超过限流阈值时,实时查价可能会被拦截。实时查价是进入订单流程的关键环节,期望实时查价尽量不限流。
kong 插件
pre-function 的优先级比 rate-limiting 高,pre-function 在access阶段根据入参设置特定的header,如X-Search-Type。缓存查价设置 X-Search-Type:price,实时查价设置X-Search-Type:check。
rate-limiting 设置通过 X-Search-Type 头来限流,相当于缓存查价和实时查价设置了相同的限流,但由于实时查价的qps远低于缓存查价,所以满足了要求。
- pre-function access 阶段的脚本
入参为json格式
local kong = kong
local cjson = require("cjson.safe")local req_body = kong.request.get_raw_body()
if req_body thenlocal decoded_body = cjson.decode(req_body)if decoded_body and decoded_body.searchType and decoded_body.searchType ~= "" thenkong.service.request.set_header("X-Search-Type", "check")elsekong.service.request.set_header("X-Search-Type", "price")end
end
konga-kong-postgres 三件套
docker-compose.yml
version: "3"networks:kong-net:driver: bridgeservices:kong-database:image: postgres:9.6restart: alwaysnetworks:- kong-netenvironment:POSTGRES_PASSWORD: kongPOSTGRES_USER: kongPOSTGRES_DB: kongports:- "5432:5432"healthcheck:test: ["CMD", "pg_isready", "-U", "kong"]interval: 5stimeout: 5sretries: 5kong-migration:image: kong:2.2.1-ubuntucommand: "kong migrations bootstrap"networks:- kong-netrestart: on-failureenvironment:KONG_PG_HOST: kong-databaseKONG_DATABASE: postgresKONG_PG_PASSWORD: konglinks:- kong-databasedepends_on:- kong-databasekong:image: kong:2.2.1-ubunturestart: alwaysnetworks:- kong-netenvironment:KONG_DATABASE: postgresKONG_PG_HOST: kong-databaseKONG_PG_USER: kongKONG_PG_PASSWORD: kongKONG_PROXY_LISTEN: 0.0.0.0:8000KONG_PROXY_LISTEN_SSL: 0.0.0.0:8443KONG_ADMIN_LISTEN: 0.0.0.0:8001KONG_PROXY_ACCESS_LOG: /dev/stdoutKONG_ADMIN_ACCESS_LOG: /dev/stdoutKONG_PROXY_ERROR_LOG: /dev/stderrKONG_ADMIN_ERROR_LOG: /dev/stderrdepends_on:- kong-migration- kong-databasehealthcheck:test: ["CMD", "curl", "-f", "http://kong:8001"]interval: 5stimeout: 2sretries: 15ports:- "8001:8001"- "8000:8000"konga-prepare:image: pantsel/konga:0.14.9command: "-c prepare -a postgres -u postgresql://kong:kong@kong-database:5432/postgres"environment:DB_ADAPTER: postgresDB_HOST: kong-databaseDB_USER: kongDB_PASSWORD: kongnetworks:- kong-netrestart: on-failurelinks:- kong-databasedepends_on:- kong-databasekonga:image: pantsel/konga:0.14.9restart: alwaysnetworks:- kong-netenvironment:DB_ADAPTER: postgresDB_HOST: kong-databaseDB_USER: kongDB_PASSWORD: kongDB_DATABASE: postgresNODE_ENV: productiondepends_on:- kong-databaseports:- "1337:1337"
总结
这里只是根据入参限流的简单实现,不支持根据入参设置不同的限流阈值。要实现更复杂的限流,可以自定义插件,或者下降到服务层处理。