Kong 如何检测连接超时?

问题描述

目前,只要上游服务宕机,kong就会抛出 "{"message":"无法从环平衡器获得对等点"}"

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

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

但这似乎也没有检测到超时。

有谁知道在编写自定义 kong 插件时我应该怎么做来检测连接超时?

解决方法

对不起,我没有抓住你。因为我不知道你的函数会返回什么

如果 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 Docs

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

您可以尝试 print(kong.response.get_source()) 并查看结果。