无服务器 - 区域、内存大小、超时



在上一章中,我们学习了如何使用无服务器部署我们的第一个函数。本章我们将探讨可以对函数执行的一些配置。我们将主要关注区域、内存大小和超时。

区域

默认情况下,使用无服务器部署的所有 Lambda 函数都创建在 us-east-1 区域。如果希望 Lambda 函数创建在其他区域,可以在提供程序中指定。

provider:
   name: aws
   runtime: python3.6
   region: us-east-2
   profile: yash-sanghvi

无法在同一个 serverless.yml 文件中为不同的函数指定不同的区域。同一个 serverless.yml 文件中应仅包含属于单个区域的函数。属于单独区域的函数可以使用单独的 serverless.yml 文件部署。

内存大小

AWS Lambda 会根据选择的内存分配 CPU。随着最近宣布的更改,您可以为 Lambda 函数选择高达 10GB 的 RAM(之前约为 3GB)。

选择的 RAM 越高,分配的 CPU 就越高,函数执行速度越快,执行时间就越短。AWS Lambda 按消耗的 GB-秒收费。因此,如果 1GB RAM 上的函数执行需要 10 秒,而 2GB RAM 上的函数执行需要 5 秒,则两次调用将收取相同的费用。内存加倍后时间是否减半很大程度上取决于函数的性质,您可能会或可能不会从增加内存中受益。关键要点是分配的内存大小是每个 Lambda 函数的重要设置,您希望能够控制它。

使用无服务器,可以很容易地为 serverless.yml 文件中定义的函数设置内存大小的默认值。也可以为不同的函数定义不同的内存大小。让我们看看如何操作。

设置所有函数的默认内存大小

默认值始终在提供程序中提及。此值将被该 serverless.yml 中的所有函数继承。memorySize 密钥用于设置此值。该值以 MB 为单位。

provider:
   name: aws
   runtime: python3.6
   region: us-east-2
   profile: yash-sanghvi
   memorySize: 512 #will be inherited by all functions

如果您没有在提供程序中或各个函数中指定 memorySize,则将考虑默认值 1024。

为某些函数设置自定义内存大小

如果希望某些函数的值不同于默认内存,则可以在 serverless.yml 的 functions 部分中指定。

functions:
   custom_memory_func: #will override the default memorySize
      handler: handler.custom_memory
      memorySize: 2048
  default_memory_func: #will inherit the default memorySize from provider
      handler: handler.default_memory

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

超时

与 memorySize 一样,超时(以秒为单位)的默认值可以在提供程序中设置,并且可以在 functions 部分中为各个函数指定自定义超时。

如果您没有指定全局或自定义超时,则默认值为 6 秒。

provider:
   name: aws
   runtime: python3.6
   region: us-east-2
   profile: yash-sanghvi
   memorySize: 512 #will be inherited by all functions
   timeout: 50 #will be inherited by all functions
  
functions:
   custom_timeout: #will override the default timeout
      handler: handler.custom_memory
      timeout: 30
  default_timeout_func: #will inherit the default timeout from provider
      handler: handler.default_memory

确保将超时保持在保守的值。它不应太小以至于您的函数频繁超时,也不应太大以至于函数中的错误导致您支付过高的账单。

广告