Kong API文档踩坑总结
在使用Kong作为API网关的过程中,遇到一个关于API文档生成的严重问题。最近在部署Kong 3.0版本时,发现通过kong-plugin-openapi插件生成的Swagger文档存在路由映射错误。
问题描述
当我们为服务配置了/api/v1/users路径,并期望在文档中看到正确的API端点时,实际生成的文档中所有路径都变成了/。这个问题导致前端团队无法正确解析API文档,造成联调阻塞。
复现步骤
- 部署Kong 3.0,启用openapi插件:
kong plugins add --name openapi --config.enable_openapi=true
- 创建服务和路由:
local kong = require "kong"
local http = require "socket.http"
-- 服务配置
kong.client.request.set_header("Content-Type", "application/json")
- 在Kong Admin API中创建路由:
{
"name": "user-service",
"paths": ["/api/v1/users"],
"service": {"id": "service-id"}
}
解决方案
经过排查发现是Kong的路由优先级配置问题。在kong.yml中需要明确指定路由的priority字段,并且确保openapi插件配置正确:
_format_version: "2.1"
services:
- name: user-service
url: http://user-service:8000
routes:
- name: user-service-route
paths:
- /api/v1/users
priority: 100
plugins:
- name: openapi
config:
enable_openapi: true
hide_credentials: true
另外,需要重启Kong服务并清除缓存:
kong reload
rm -rf /usr/local/kong/cache/
实战经验
在生产环境中,建议使用kong-plugin-openapi的openapi_url参数直接指向外部文档地址,避免Kong内部解析导致的问题。同时,建议配合使用kong-plugin-request-transformer插件进行路径重写。
总结
这个踩坑经历提醒我们在生产部署中必须充分测试API文档生成功能,特别是当存在多个路由规则时,优先级配置和缓存清理是关键步骤。

讨论