背景
價格接口 /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"
總結
這里只是根據入參限流的簡單實現,不支持根據入參設置不同的限流閾值。要實現更復雜的限流,可以自定義插件,或者下降到服務層處理。