Kong如何检测连接超时?

当前,当上游服务停止运行时,Kong将抛出 "{"message":"从环形负载均衡器获取对等体失败"}"

我正在尝试创建一个自定义插件来检测连接超时并向客户端返回自定义消息,我现在面临的障碍是在我的自定义插件中编写lua代码以检测超时。 我尝试使用

if(kong.response.get_source() == "error")

但这似乎也不能检测超时。

有没有人有任何想法,在编写自定义kong插件时如何检测连接超时?

点赞
用户15878986
用户15878986

抱歉,我没有听清楚你说什么。因为我不知道你的函数会返回什么。

如果 kong.response.get_source() 返回一个字符串 {"message":"failure to get a peer from the ring-balancer"}

你需要使用 JSON 库来解析它。

local json = require("json")
local res = json.deceode(kong.response.get_source())
if res.message == "xxx" then

end

但是你的 message 有点长。你可以向 JSON 字符串中添加一个新的键值对,来代表状态。

例如:"{"status":"error","message":"failure to get a peer from the ring-balancer"}"

然后你可以这样写代码。

local json = require("json")
local res = json.deceode(kong.response.get_source())
if res.status == "error" then

end

我刚刚看了一下 Kong API 文档

我发现 kong.response.get_source() 的返回值是 HTTP 状态码,比如 200/500。

你可以尝试使用 print(kong.response.get_source()) 来查看结果。

2021-05-10 13:59:38