跳转到内容
加入 「福强私学」,学习和了解更多关于技术、管理与人生的精彩内容。

如何在HonoJS里使用Service Binding?

什么是Service Binding?

Service Binding是cloudflare workers的一个特性,简单来说就是,假如Worker1想要调用Worker2,可以直接用fetch api或者axios甚至ky等http client发起请求,但这样会导致通信走公网,请求处理时延会有很大的延迟。 如果要避免这种问题,我们可以使用cloudflare workers的service binding特性,这个特性的作用就是让worker调用worker不用走公网,减少worker调用worker之间的时延(latency)。

cloudflare官方文档中的service binding示意图

NOTE

不走service binding当然也可以,但有可能遭遇错误: error code: 522

在cloudflare workers原始API方式中使用service binding

要使用service bingding,我们需要在当前worker的配置文件中首先添加service binding的配置:

[[services]]
binding = "authflare"
service = "kauthflare"

这里我们使用kauthflare这个worker,然后用authflare作为binding的名字,以便稍后在worker程序代码中引用。

所以,下一步就是编写worker代码来调用这个service binding(以下代码来自cloudflare官方文档,但稍作了改动以应对以上配置内容):

export default {
async fetch(request, env) {
// Fetch AUTH service and pass request
const authResponse = await env.authflare.fetch(request.clone());
// Return response from the AUTH service if the response status is not 200
// It would return 403 'x-custom-token does not match, request not allowed' response in such case
if (authResponse.status !== 200) {
return authResponse;
}
// Request allowed
// You can write application logic here
// In this case we delegate the logic to an `application` Worker
return await env.application.fetch(request)
},
};

在honojs应用中使用service binding

大多数时候,福强老师现在都用honojs作为cloudflare workers的开发框架,而要在honojs中使用service binding,其实也相当简单。

第一步依然是配置,在wrangler.toml配置文件中添加上一章节同样的配置内容:

[[services]]
binding = "authflare"
service = "kauthflare"

第二步则是在hono的handler中使用这个配置好的service binding:

const accessToken = await c.env.credentials.get("X_TOKEN")
const authRequest = new Request('https://auth.xyz/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify(authPayload)
})
const authResponse = await c.env.authflare.fetch(authRequest)
if (authResponse.ok) {
// ...
return c.text("OK")
} else {
return c.text(authResponse.statusText, authResponse.status)
}

That’s it, 是不是很简单呢? 😉

加入「福强私学」

学习和了解更多关于技术、管理与人的精彩内容。

如果已经购买「福强私学」,可以直接点击这里开始访问

©️王福强个人版权所有