如何在Kong自定义插件中跳转到Konga配置的上游地址?
Kong插件根据配置参数动态切换上游问题解决
我需要实现一个Kong插件,根据插件的配置参数动态切换上游服务:当参数配置为1时跳转到upstream1,配置为2时跳转到upstream2。但目前实现后始终只会跳转到upstream1,因为我的路由服务器默认配置的就是upstream1。
当前我的插件代码如下:
function MyPlugin:access(plugin_conf) kong.service.set_upstream("upstream1Name") end
我知道在OpenResty配置文件里可以通过变量轻松实现这个逻辑:
proxy_pass http://$backend/myMethod
问题原因与解决方案
问题出在你当前的代码固定设置死了上游为upstream1Name,没有根据插件配置参数做分支判断。需要修改插件代码,读取plugin_conf里的配置参数,动态选择对应的上游名称:
基础分支判断实现
function MyPlugin:access(plugin_conf) -- 假设你的插件配置参数名为`upstream_type` if plugin_conf.upstream_type == 1 then kong.service.set_upstream("upstream1Name") elseif plugin_conf.upstream_type == 2 then kong.service.set_upstream("upstream2Name") else -- 设置默认上游,或者根据需求抛出错误 kong.service.set_upstream("upstream1Name") end end
优化:用映射表简化逻辑
如果需要更灵活的参数-上游映射,可使用表存储对应关系,避免过多if-else:
local upstream_map = { [1] = "upstream1Name", [2] = "upstream2Name" } function MyPlugin:access(plugin_conf) local target_upstream = upstream_map[plugin_conf.upstream_type] or "upstream1Name" kong.service.set_upstream(target_upstream) end
注意事项
- 确保插件schema中已声明对应的配置字段,比如:
fields = { upstream_type = { type = "number", required = true, one_of = {1, 2} } } - 传入
kong.service.set_upstream的上游名称,必须是Kong中已创建的上游对象名称,否则会触发错误。
内容的提问来源于stack exchange,提问作者flower
相关产品推荐
相关产品推荐

