Câu chuyện thực tế: Khi hệ thống RAG của tôi suýt "cháy" với 10.000 người dùng đồng thời
Tháng 9 năm ngoái, tôi nhận được cuộc gọi lúc 2 giờ sáng. Hệ thống RAG (Retrieval-Augmented Generation) của một doanh nghiệp thương mại điện tử lớn tại Việt Nam đang quá tải — 10.000 người dùng đồng thời truy vấn chatbot AI, nhưng backend chỉ chịu được 500 request/giây. Độ trễ tăng từ 200ms lên 15 giây. Khách hàng than phiền, đối tác lo lắng, và tôi phải giải quyết trong 4 tiếng.
Đó là lúc tôi quyết định xây dựng một AI API Gateway thực thụ — không phải một proxy đơn giản, mà là một hệ thống có rate limiting thông minh, caching lưu ý, load balancing, và quan trọng nhất: tối ưu chi phí API.
Bài viết này chia sẻ toàn bộ kinh nghiệm thực chiến, từ việc chọn giải pháp (Kong vs NGINX), đến code triển khai production-ready, và cách tôi giảm 85% chi phí API nhờ
HolySheep AI.
Tại sao cần AI API Gateway?
Trước khi đi vào chi tiết kỹ thuật, hãy hiểu tại sao AI API Gateway không chỉ là "nice-to-have" mà là "must-have" cho bất kỳ hệ thống AI nào:
- Quản lý rate limiting: Ngăn chặn việc một client đơn lẻ chiếm hết quota API của bạn
- Caching thông minh: Lưu lại các query phổ biến, giảm số lượng gọi API xuống 60-80%
- Load balancing: Phân phối request đến nhiều backend endpoint
- Authentication & Authorization: Quản lý API key tập trung, revoke key dễ dàng
- Observability: Theo dõi latency, error rate, chi phí theo từng endpoint và client
- Tối ưu chi phí: Route request thông minh, chọn model phù hợp với từng loại task
So sánh Kong vs NGINX: Chọn giải pháp nào cho AI Gateway?
Đây là quyết định quan trọng đầu tiên. Dựa trên kinh nghiệm triển khai thực tế, đây là bảng so sánh chi tiết:
| Tiêu chí |
Kong Gateway |
NGINX |
| Độ phức tạp setup |
Trung bình (Docker compose 5 phút) |
Thấp (config file đơn giản) |
| Plugin ecosystem |
Rất phong phú (rate limiting, auth, caching có sẵn) |
Cần tự viết Lua/Module |
| Performance |
~50,000 req/s trên 2 core |
~100,000 req/s trên 2 core |
| Dashboard |
Kong Manager (GUI có sẵn) |
Không có (cần third-party) |
| Database |
PostgreSQL/Cassandra (optional) |
Không cần |
| Clustering |
Native support với Kong Gateway |
Cần thêm Keepalived |
| AI-specific features |
Plugin cho OpenAI, Claude (cần config) |
Phải tự xây dựng |
| Giá |
Open source miễn phí |
Open source miễn phí |
Khuyến nghị của tôi:
- Chọn Kong nếu: Cần nhanh chóng triển khai, muốn sử dụng plugin có sẵn, cần dashboard để quản lý, team có kinh nghiệm với microservices
- Chọn NGINX nếu: Cần performance tối đa, hệ thống đơn giản, muốn minimal dependencies, đã quen với NGINX config
Phương án 1: Xây dựng AI API Gateway với Kong
Triển khai với Docker Compose
Dưới đây là cấu hình production-ready sử dụng Kong Gateway với PostgreSQL cho lưu trữ plugin configuration:
version: '3.8'
services:
kong-database:
image: postgres:15
container_name: ai-gateway-kong-db
environment:
POSTGRES_DB: kong
POSTGRES_USER: kong
POSTGRES_PASSWORD: kong_secure_password_2026
volumes:
- kong-db-data:/var/lib/postgresql/data
networks:
- ai-gateway-net
restart: unless-stopped
kong-migration:
image: kong:latest
container_name: ai-gateway-migration
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_USER: kong
KONG_PG_PASSWORD: kong_secure_password_2026
KONG_DATABASE: postgres
command: kong migrations bootstrap
networks:
- ai-gateway-net
depends_on:
- kong-database
restart: on-failure
kong:
image: kong:latest
container_name: ai-gateway-kong
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_USER: kong
KONG_PG_PASSWORD: kong_secure_password_2026
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_ADMIN_ERROR_LOG: /dev/stderr
KONG_ADMIN_LISTEN: 0.0.0.0:8001, 0.0.0.0:8444 ssl
ports:
- "8000:8000" # Proxy HTTP
- "8443:8443" # Proxy HTTPS
- "8001:8001" # Admin API HTTP
- "8444:8444" # Admin API HTTPS
volumes:
- ./kong/plugins:/usr/local/share/lua/5.1/kong/plugins:ro
networks:
- ai-gateway-net
depends_on:
- kong-migration
restart: unless-stopped
redis:
image: redis:7-alpine
container_name: ai-gateway-redis
command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
volumes:
- redis-data:/data
networks:
- ai-gateway-net
restart: unless-stopped
prometheus:
image: prom/prometheus:latest
container_name: ai-gateway-prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
networks:
- ai-gateway-net
restart: unless-stopped
networks:
ai-gateway-net:
driver: bridge
volumes:
kong-db-data:
redis-data:
Cấu hình AI API Routes và Plugins
Đây là phần quan trọng nhất — cấu hình routes và plugins cho AI Gateway. Tôi sử dụng Kong Admin API:
# ============================================
1. Thêm Consumer (Client) cho AI Gateway
============================================
curl -X POST http://localhost:8001/consumers \
--data "username=ecommerce-chatbot" \
--data "custom_id=client-001"
curl -X POST http://localhost:8001/consumers \
--data "username=rag-system" \
--data "custom_id=client-002"
Tạo API Key cho consumer
curl -X POST http://localhost:8001/consumers/ecommerce-chatbot/key-auth \
--data "key=sk-holysheep-ecommerce-2026-secure"
curl -X POST http://localhost:8001/consumers/rag-system/key-auth \
--data "key=sk-holysheep-rag-2026-secure"
============================================
2. Cấu hình Upstream (Backend Target)
============================================
Thêm upstream cho HolySheep AI API
curl -X POST http://localhost:8001/upstreams \
--data "name=ai-api-holysheep" \
--data "algorithm=least-connections" \
--data "healthchecks.active.timeout=5" \
--data "healthchecks.active.healthy.interval=5"
Thêm target với health check
curl -X POST http://localhost:8001/upstreams/ai-api-holysheep/targets \
--data "target=api.holysheep.ai:443" \
--data "weight=100"
============================================
3. Tạo Service cho AI Endpoints
============================================
Service cho chat completions
curl -X POST http://localhost:8001/services \
--data "name=ai-chat-service" \
--data "url=https://api.holysheep.ai/v1/chat/completions" \
--data "connect_timeout=30000" \
--data "read_timeout=120000" \
--data "write_timeout=120000"
Service cho embeddings
curl -X POST http://localhost:8001/services \
--data "name=ai-embedding-service" \
--data "url=https://api.holysheep.ai/v1/embeddings" \
--data "connect_timeout=10000" \
--data "read_timeout=30000"
Service cho completions (legacy)
curl -X POST http://localhost:8001/services \
--data "name=ai-completion-service" \
--data "url=https://api.holysheep.ai/v1/completions"
============================================
4. Tạo Routes
============================================
Route cho chat completions
curl -X POST http://localhost:8001/services/ai-chat-service/routes \
--data "name=chat-route" \
--data "paths[]=/ai/v1/chat/completions" \
--data "methods[]=POST" \
--data "strip_path=false"
Route cho embeddings
curl -X POST http://localhost:8001/services/ai-embedding-service/routes \
--data "name=embedding-route" \
--data "paths[]=/ai/v1/embeddings" \
--data "methods[]=POST"
Route cho models list
curl -X POST http://localhost:8001/services/ai-chat-service/routes \
--data "name=models-route" \
--data "paths[]=/ai/v1/models" \
--data "methods[]=GET"
============================================
5. Cấu hình Rate Limiting Plugin
============================================
Rate limit cho chat: 100 req/phút/client
curl -X POST http://localhost:8001/services/ai-chat-service/plugins \
--data "name=rate-limiting" \
--data "config.minute=100" \
--data "config.policy=redis" \
--data "config.redis_host=redis" \
--data "config.redis_port=6379" \
--data "config.hide_client_headers=false"
Rate limit riêng cho consumer
curl -X POST http://localhost:8001/consumers/ecommerce-chatbot/plugins \
--data "name=rate-limiting" \
--data "config.minute=200" \
--data "config.policy=redis"
============================================
6. Cấu hình Key Auth Plugin
============================================
curl -X POST http://localhost:8001/services/ai-chat-service/plugins \
--data "name=key-auth" \
--data "config.key_names=apikey,X-API-Key" \
--data "config.key_in_header=true"
============================================
7. Cấu hình CORS
============================================
curl -X POST http://localhost:8001/services/ai-chat-service/plugins \
--data "name=cors" \
--data "config.origins=*" \
--data "config.methods=GET,POST,OPTIONS" \
--data "config.headers=Content-Type,apikey,Authorization" \
--data "config.exposed_headers=X-RateLimit-Limit,X-RateLimit-Remaining" \
--data "config.credentials=true" \
--data "config.max_age=3600"
============================================
8. Cấu hình Response Caching
============================================
Cache các request GET (models list)
curl -X POST http://localhost:8001/routes/models-route/plugins \
--data "name=proxy-cache" \
--data "config.response_code=200" \
--data "config.request_method=GET" \
--data "config.cache_ttl=3600" \
--data "config.strategy=redis"
============================================
9. Cấu hình Prometheus Metrics
============================================
curl -X POST http://localhost:8001/plugins \
--data "name=prometheus" \
--data "config.per_consumer=true"
Phương án 2: Xây dựng AI API Gateway với NGINX
Cấu hình NGINX cho AI Gateway
Nếu bạn chọn NGINX vì đơn giản và performance cao, đây là cấu hình production-ready:
# nginx.conf - AI API Gateway Configuration
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging format với latency tracking
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
# Performance optimizations
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
# Rate limiting zones
limit_req_zone $binary_remote_addr zone=ai_general:10m rate=50r/s;
limit_req_zone $http_x_api_key zone=ai_per_key:10m rate=100r/m;
limit_conn_zone $binary_remote_addr zone=addr:10m;
# Upstream cho HolySheep AI
upstream ai_backend {
server api.holysheep.ai:443;
keepalive 32;
keepalive_timeout 60s;
}
# Cache configuration
proxy_cache_path /var/cache/nginx/ai_cache
levels=1:2
keys_zone=ai_cache:100m
max_size=1g
inactive=1h
use_temp_path=off;
# Main server - AI Gateway
server {
listen 80;
listen [::]:80;
server_name ai-gateway.local;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Health check endpoint
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# Proxy đến HolySheep AI với các tính năng gateway
location ~ ^/v1/(chat/completions|completions|embeddings) {
# Rate limiting
limit_req zone=ai_general burst=20 nodelay;
limit_req zone=ai_per_key burst=10 nodelay;
limit_conn addr 10;
# Proxy settings
proxy_pass https://ai_backend;
proxy_http_version 1.1;
# Headers forwarding
proxy_set_header Host api.holysheep.ai;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Preserve original API key/Authorization
proxy_set_header Authorization $http_authorization;
proxy_set_header apikey $http_apikey;
# Timeout settings cho AI requests
proxy_connect_timeout 30s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;
# Buffering
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# Response caching (chỉ cho GET requests)
proxy_cache_valid 200 1h;
proxy_cache_key "$scheme$request_method$host$request_uri$http_apikey";
proxy_cache_bypass $http_cache_control;
add_header X-Cache-Status $upstream_cache_status;
}
# Models list endpoint (cache lâu hơn)
location ~ ^/v1/models {
# Longer cache cho models list
proxy_cache_valid 200 24h;
proxy_cache_lock on;
proxy_cache_use_stale updating;
limit_req zone=ai_general burst=5 nodelay;
proxy_pass https://ai_backend;
proxy_http_version 1.1;
proxy_set_header Host api.holysheep.ai;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Cache headers
add_header Cache-Control "public, max-age=86400";
}
# Error pages
error_page 429 = @rate_limit_exceeded;
error_page 500 502 503 504 = @backend_error;
location @rate_limit_exceeded {
default_type application/json;
return 429 '{"error":{"message":"Rate limit exceeded. Please slow down.","type":"rate_limit_error"}}';
}
location @backend_error {
default_type application/json;
return 503 '{"error":{"message":"AI service temporarily unavailable. Please try again.","type":"service_unavailable"}}';
}
}
# HTTPS server (khuyến nghị sử dụng trong production)
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ai-gateway.local;
# SSL Configuration
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# Copy các location từ server 80 vào đây
# (Đã简化 cho ngắn gọn - trong thực tế cần copy toàn bộ)
include /etc/nginx/conf.d/ai-locations.conf;
}
}
Lua Module cho Rate Limiting Nâng cao (NGINX)
Để có rate limiting thông minh hơn với NGINX, bạn có thể sử dụng Lua:
-- lua_rate_limiter.lua
-- Advanced Rate Limiting với Redis cho NGINX
local redis = require "resty.redis"
local cjson = require "cjson"
local _M = {}
-- Kết nối Redis
local function connect_redis()
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("redis", 6379)
if not ok then
return nil, err
end
return red
end
-- Lấy API key từ request
local function get_api_key()
local key = ngx.var.http_apikey or ngx.var.http_Authorization
if key then
key = key:gsub("Bearer%s+", "")
end
return key
end
-- Kiểm tra và cập nhật rate limit
function _M.check_rate_limit()
local red, err = connect_redis()
if not red then
ngx.log(ngx.ERR, "Redis connection failed: ", err)
return true -- Allow request nếu Redis down
end
local api_key = get_api_key() or ngx.var.binary_remote_addr
local limit_type = "per_key"
-- Nếu không có API key, sử dụng IP
if not ngx.var.http_apikey and not ngx.var.http_Authorization then
api_key = "ip:" .. ngx.var.binary_remote_addr
limit_type = "per_ip"
else
api_key = "key:" .. api_key
end
local now = ngx.now()
local window = 60 -- 1 phút window
local limit = 100 -- requests per window
-- Key riêng cho consumer VIP (có thể mở rộng từ database)
local vip_keys = {
["sk-holysheep-ecommerce-2026-secure"] = 200,
["sk-holysheep-rag-2026-secure"] = 500
}
local key_hash = ngx.md5(api_key)
local redis_key = "ratelimit:" .. key_hash .. ":" .. limit_type
-- Atomic rate limiting với Redis
local res, err = red:eval([[
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
-- Remove expired entries
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
-- Count current requests
local count = redis.call('ZCARD', key)
if count < limit then
redis.call('ZADD', key, now, now .. '-' .. math.random())
redis.call('EXPIRE', key, window)
return {1, limit - count - 1}
else
return {0, 0}
end
]], 1, redis_key, limit, window, now)
local ok, err = red:set_keepalive(10000, 10)
if not ok then
ngx.log(ngx.WARN, "Failed to set keepalive: ", err)
end
if res[1] == 0 then
ngx.header["X-RateLimit-Limit"] = limit
ngx.header["X-RateLimit-Remaining"] = 0
ngx.header["X-RateLimit-Reset"] = now + window
ngx.header["Retry-After"] = window
ngx.status = 429
ngx.say(cjson.encode({
error = {
message = "Rate limit exceeded. Please wait before making more requests.",
type = "rate_limit_error",
retry_after = window
}
}))
ngx.exit(ngx.HTTP_TOO_MANY_REQUESTS)
else
-- Lấy thông tin rate limit từ request tiếp theo
local remaining = tonumber(res[2])
ngx.header["X-RateLimit-Limit"] = limit
ngx.header["X-RateLimit-Remaining"] = remaining
ngx.header["X-RateLimit-Reset"] = now + window
end
end
-- Logging metrics
function _M.log_request()
local api_key = get_api_key() or "anonymous"
local metric_key = "metrics:" .. ngx.md5(api_key)
local red, err = connect_redis()
if red then
local now = os.time()
red:zadd(metric_key, now, now .. "-req-" .. ngx.var.request_id)
red:expire(metric_key, 86400)
red:set_keepalive(10000, 10)
end
end
return _M
Cách sử dụng Gateway với Code Example
Sau khi đã triển khai Gateway, đây là cách client sử dụng:
# Python client example cho AI Gateway
Sử dụng với Kong hoặc NGINX gateway
import requests
import json
from typing import Optional, Dict, Any
import time
class AIAIGatewayClient:
"""
Client cho AI Gateway với automatic retry, rate limit handling,
và fallback mechanism.
"""
def __init__(
self,
base_url: str = "http://localhost:8000",
api_key: str = "sk-holysheep-ecommerce-2026-secure",
timeout: int = 120,
max_retries: int = 3
):
self.base_url = base_url.rstrip('/')
self.api_key = api_key
self.timeout = timeout
self.max_retries = max_retries
self.session = requests.Session()
self.session.headers.update({
"Content-Type": "application/json",
"apikey": self.api_key
})
def chat_completions(
self,
model: str = "gpt-4.1",
messages: list[Dict[str, str]],
temperature: float = 0.7,
max_tokens: Optional[int] = None,
**kwargs
) -> Dict[str, Any]:
"""
Gọi chat completions API thông qua gateway.
Args:
model: Model name (gpt-4.1, claude-sonnet-4.5, gemini-2.5-flash, deepseek-v3.2)
messages: List of message objects
temperature: Sampling temperature
max_tokens: Maximum tokens to generate
**kwargs: Additional parameters
Returns:
API response as dictionary
"""
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
**kwargs
}
if max_tokens:
payload["max_tokens"] = max_tokens
return self._make_request(
method="POST",
endpoint="/v1/chat/completions",
payload=payload
)
def embeddings(
self,
input_text: str | list[str],
model: str = "text-embedding-3-small"
) -> Dict[str, Any]:
"""
Tạo embeddings thông qua gateway.
"""
payload = {
"model": model,
"input": input_text
}
return self._make_request(
method="POST",
endpoint="/v1/embeddings",
payload=payload
)
def _make_request(
self,
method: str,
endpoint: str,
payload: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Make request với automatic retry và error handling.
"""
url = f"{self.base_url}{endpoint}"
last_error = None
for attempt in range(self.max_retries):
try:
if method == "POST":
response = self.session.post(
url,
json=payload,
timeout=self.timeout
)
else:
response = self.session.get(
url,
timeout=self.timeout
)
# Check rate limit
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
print(f"Rate limited. Waiting {retry_after} seconds...")
time.sleep(retry_after)
continue
# Check other errors
if response.status_code >= 500:
wait_time = 2 ** attempt
print(f"Server error {response.status_code}. Retry in {wait_time}s...")
time.sleep(wait_time)
continue
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
last_error = f"Request timeout after {self.timeout}s"
print(f"Attempt {attempt + 1} failed: {last_error}")
except requests.exceptions.RequestException as e:
last_error = str(e)
print(f"Attempt {attempt + 1} failed: {last_error}")
if attempt < self.max_retries - 1:
time.sleep(2 ** attempt)
raise Exception(f"Request failed after {self.max_retries} attempts: {last_error}")
Sử dụng example
if __name__ == "__main__":
# Khởi tạo client
client = AIAIGatewayClient(
base_url="http://localhost:8000",
api_key="sk-holysheep-ecommerce-2026-secure"
)
# Chat completion example
try:
response = client.chat_completions(
model="gpt-4.1", # Hoặc claude-sonnet-4.5, gemini-2.5-flash, deepseek-v3.2
messages=[
{"role": "system", "content": "Bạn là trợ lý AI hữu ích."},
{"role": "user", "content": "Xin chào, hãy giới thiệu về HolySheep AI"}
],
temperature=0.7,
max_tokens=500
)
print("Response:", response["choices"][0]["message"]["content"])
except Exception as e:
print(f"Error: {e}")
# Embedding example
try:
embeddings = client.embeddings(
input_text="Tìm kiếm thông tin về sản phẩm",
model="text-embedding-3-small"
)
print("Embedding dimension:", len(embeddings["data"][0]["embedding"]))
except Exception as e:
print(f"Embedding error: {e}")
Monitoring và Observability
Để theo dõi AI Gateway hiệu quả, tôi khuyến nghị sử dụng Prometheus + Grafana:
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'kong-gateway'
static_configs:
- targets: ['kong:8001']
metrics_path: /metrics
scheme: http
- job_name: 'nginx-gateway'
static_configs:
- targets: ['nginx:9090']
metrics_path: /metrics
scheme: http
- job_name: 'ai-upstream-health'
static_configs:
- targets: ['api.holysheep.ai']
metrics_path: /health
scheme: https
tls_config:
insecure_skip_verify: false
Lỗi thường gặp và cách khắc phục
Lỗi 1: Kong Gateway trả về 401 Unauthorized dù API key đúng
Nguyên nhân: Kong không nhận diện được API key từ header không chuẩn.
Giải pháp:
# Kiểm tra key-auth plugin configuration
Đảm bảo key_names chứa đúng header name client sử dụng
Nếu client gửi header là "apikey" (không phải "api-key")
curl -X POST http://localhost:8001/services/ai-chat-service/plugins \
--data "name=key-auth" \
--data "config.key_names=apikey,api_key,Authorization" \
--data "config.key_in_header=true" \
--data "config.key_in_query=false"
Hoặc nếu dùng query parameter
curl -X POST http://localhost:8001/services/ai-chat-service/plugins \
--data "name=key-auth" \
--data "config.key_names=apikey" \
--data "config.key_in_header=true" \
--data "config.key_in_query=true"
Debug: Kiểm tra consumer và key đã tồn tại
curl http://localhost:8001/consumers/ecommerce-chatbot/key-auth
Output mong đợi:
{"data":[{"created_at":
Tài nguyên liên quan
Bài viết liên quan