KrakenD顺序调用后端:如何传递响应并动态设置主机?
KrakenD动态设置后端主机解决方案
核心思路
通过Lua脚本将第一个后端的响应数据存入请求上下文,再在第二个后端的前置逻辑中读取该数据,动态修改请求的目标主机。
具体实现步骤
- 修改第一个后端的Lua后置脚本:在第一个后端(a.com)的响应处理完成后,提取返回的
host字段,存入请求上下文。 - 修改第二个后端的Lua前置脚本:在第二个后端发起请求前,从上下文读取存储的
host值,动态设置请求的目标主机。 - 调整配置中的占位符:移除第二个后端
host配置中的静态占位符,让Lua脚本直接修改请求的主机。
修改后的KrakenD配置
{"$schema": "https://www.krakend.io/schema/krakend.json", "version": 3, "name": "Test Proxying & Microservices", "timeout": "3000ms", "cache_ttl": "300s", "endpoints": [ { "endpoint": "/protected/{path}", "extra_config": { "proxy": { "sequential": true } }, "backend": [ { "encoding": "no-op", "@comment": "Authentication Service", "url_pattern": "/api/v1/allocations", "method": "GET", "host": ["https://a.com"], "disable_host_sanitize": false, "extra_config": { "modifier/lua-backend": { "sources": ["authz.lua"], "allow_open_libs": true, "post": "local resp = response.load()\nlocal resp_body = resp:body()\nlocal data = require('cjson').decode(resp_body)\n-- 将host存入请求上下文\nrequest.set_context('target_host', data.host)" } } }, { "@comment": "Genesist Base", "encoding": "no-op", "url_pattern": "/{path}", "host": ["https://placeholder.com"], -- 占位符,实际由Lua修改 "extra_config": { "modifier/lua-backend": { "sources": ["authz.lua"], "allow_open_libs": true, "pre": "local target_host = request.get_context('target_host')\nif target_host then\n -- 动态设置请求的主机\n request.set_host('https://' .. target_host .. '.com')\nend" } } } ] } ] }
关键说明
- 必须确保
sequential配置为true,保证两个后端按顺序执行。 - 使用
request.set_context和request.get_context实现跨后端的数据共享,这是KrakenD官方推荐的跨后端传值方式。 - 第二个后端的
host配置仅需填写占位符,Lua脚本会在请求发送前替换为实际的主机地址。
内容的提问来源于stack exchange,提问作者Leight
相关产品推荐
相关产品推荐

