边缘函数

区域调用

如何在特定区域执行边缘函数。


边缘函数会在距离发起请求的用户最近的区域执行,这有助于减少网络延迟并为用户提供更快的响应。

然而,如果您的函数需要执行大量数据库或存储操作,在与数据库相同的区域调用函数可能会获得更好的性能。以下情况特别适用:

  • 批量添加和编辑数据库记录
  • 上传文件

Supabase 提供了在调用函数时指定区域的选项。

使用 x-region 请求头

在调用边缘函数时,使用 x-region HTTP 请求头来指定函数执行区域:

1
2
3
4
5
6
# https://supabase.com/docs/guides/functions/deploy#invoking-remote-functionscurl --request POST 'https://<project_ref>.supabase.co/functions/v1/hello-world' \ --header 'Authorization: Bearer ANON_KEY' \ --header 'Content-Type: application/json' \ --header 'x-region: eu-west-3' \ --data '{ "name":"Functions" }'

您可以通过查看响应中的 x-sb-edge-region HTTP 请求头来验证执行区域。也可以在边缘函数日志中查看该元数据。

可用区域

以下是当前支持的 x-region 请求头可用的区域值:

  • ap-northeast-1
  • ap-northeast-2
  • ap-south-1
  • ap-southeast-1
  • ap-southeast-2
  • ca-central-1
  • eu-central-1
  • eu-west-1
  • eu-west-2
  • eu-west-3
  • sa-east-1
  • us-east-1
  • us-west-1
  • us-west-2

使用客户端库

您也可以在调用函数时通过 Supabase 客户端库指定区域:

1
2
3
4
5
6
7
8
9
import { , } from '@supabase/supabase-js'const = ('SUPABASE_URL', 'SUPABASE_ANON_KEY')const { : , } = await ..('my-function-name', { : { 'Content-Type': 'application/json' }, : 'GET', : {}, : .,})

处理区域中断

如果您通过 x-region 请求头显式指定了区域,请求不会自动重路由到其他区域,在中断期间您应考虑临时切换到其他区域。