简体   繁体   English

设计无服务器 function 与常规服务器的差异

[英]Differences in designing a serverless function vs. regular server

I am wondering what approach in designing serverless functions to take, while taking designing a regular server as a point of reference.我想知道在设计无服务器功能时采用什么方法,同时将设计常规服务器作为参考点。

With a traditional server, one would focus on defining collections and then CRUD operations one can run on each of them (HTTP verbs such as GET or POST).对于传统服务器,人们会专注于定义 collections,然后可以在每个服务器上运行 CRUD 操作(HTTP 动词,例如 GET 或 POST)。 For example, you would have a collection of users , and you can get all records via app.get('/users', ...) , get specific one via app.get('/users/{id}', ...) or create one via app.post('/users', ...) .例如,您将有一组users ,您可以通过app.get('/users', ...)获取所有记录,通过app.get('/users/{id}', ...)或通过app.post('/users', ...)创建一个。

How differently would you approach designing a serverless function?您设计无服务器 function 的方法有何不同? Specifically:具体来说:

  1. Is there a sense in differentiating between HTTP operations or would you just go with POST?区分 HTTP 操作是否有意义,或者您只是 go 与 POST? I find it useful to have them defined on the client side, to decide if I want to retry in case of an error (if the operation is idempotent, it will be safe to retry etc.), but it does not seem to matter in the back-end.我发现在客户端定义它们很有用,可以决定在出现错误时是否要重试(如果操作是幂等的,重试是安全的等等),但这似乎并不重要后端。
  2. Naming.命名。 I assume you would use something like getAllUsers() when with a regular server you would define collection of users and then just use GET to specify what you want to do with it.我假设您在使用常规服务器时会使用类似getAllUsers()的方法来定义users集合,然后仅使用 GET 来指定您要对其执行的操作。
  3. Size of functions: if you need to do a number of things in the back-end in one step.功能规模:如果你需要一步在后端做很多事情。 Would you define a number of small functions, such as lookupUser() , endTrialForUser() (fired if user we got from lookupUser() has been on trial longer than 7 days) etc. and then run them one after another from the client (deciding if trial should be ended on the client - seems quite unsafe), or would you just create a getUser() and then handle all the logic there?你会定义一些小函数,比如lookupUser()endTrialForUser() (如果我们从lookupUser()得到的用户试用时间超过 7 天,就会触发)等等,然后从客户端一个接一个地运行它们(决定是否应该在客户端结束试用 - 似乎很不安全),或者你会创建一个getUser()然后处理那里的所有逻辑吗?
  4. Routing.路由。 In serverless functions, we can't really do anything like .../users/${id}/accountData .在无服务器函数中,我们不能真正做任何类似.../users/${id}/accountData的事情。 How would you go around fetching nested data?您 go 如何获取嵌套数据? Would you just return a complete JSON every time?你会不会每次都返回一个完整的JSON?

I have been looking for some comprehensive articles on the matter but no luck.我一直在寻找有关此事的一些综合文章,但没有运气。 Any suggestions?有什么建议么?

This is a very broad question that you've asked.这是您提出的一个非常广泛的问题。 Let me try answering it point by point.让我试着逐点回答。

Firstly, the approach that you're talking about here is the Serverless API project approach.首先,您在这里谈论的方法是Serverless API项目方法。 You can clone their sample project to get a better understanding of how you can build REST apis for performing CRUD operations.您可以克隆他们的示例项目,以更好地了解如何构建REST api 来执行CRUD操作。 Start by installing the SAM cli and then run the following commands.首先安装 SAM cli ,然后运行以下命令。

$ sam init
Which template source would you like to use?
    1 - AWS Quick Start Templates
    2 - Custom Template Location
Choice: 1

Cloning from https://github.com/aws/aws-sam-cli-app-templates

Choose an AWS Quick Start application template
    1 - Hello World Example
    2 - Multi-step workflow
    3 - Serverless API
    4 - Scheduled task
    5 - Standalone function
    6 - Data processing
    7 - Infrastructure event management
    8 - Machine Learning
Template: 3

Which runtime would you like to use?
    1 - dotnetcore3.1
    2 - nodejs14.x
    3 - nodejs12.x
    4 - python3.9
    5 - python3.8
Runtime: 2

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is npm.
We will proceed copying the template using npm.

Project name [sam-app]: sample-app

    -----------------------
    Generating application:
    -----------------------
    Name: sample-app
    Runtime: nodejs14.x
    Architectures: x86_64
    Dependency Manager: npm
    Application Template: quick-start-web
    Output Directory: .
    
    Next steps can be found in the README file at ./sample-app/README.md
        

    Commands you can use next
    =========================
    [*] Create pipeline: cd sample-app && sam pipeline init --bootstrap
    [*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
Comings to your questions point wise:明智地回答您的问题:
  1. Yes, you should differentiate your HTTP operations with their suitableHTTP verbs .是的,您应该将您的HTTP操作与其合适的HTTP verbs This can be configured at the API Gateway and can be checked for in the Lambda code.这可以在 API 网关配置,可以在 Lambda 代码中检查。 Check the source code of handlers & the template.yml file from the project you've just cloned with SAM .检查处理程序的源代码和您刚刚使用SAM克隆的项目中的template.yml文件。
   // src/handlers/get-by-id.js
   if (event.httpMethod !== 'GET') {
        throw new Error(`getMethod only accepts GET method, you tried: ${event.httpMethod}`);
   }
   # template.yml
   Events:
       Api:
         Type: Api
         Properties:
           Path: /{id}
           Method: GET
  1. The naming is totally up to the developer.命名完全取决于开发人员。 You can follow the same approach that you're following with your regular server project.您可以采用与常规服务器项目相同的方法。 You can define the handler with name getAllUsers or users and then set the path of that resource to GET /users in the AWS API Gateway .您可以使用名称getAllUsersusers定义处理程序,然后将该资源的路径设置为AWS API Gateway中的GET /users You can choose theHTTP verbs of your desire.您可以选择您想要的HTTP verbs Check this tutorial out for better understanding.查看教程以获得更好的理解。

  2. Again this up to you.这又取决于你。 You can create a single Lambda that handles all that logic or create individual Lambdas that are triggered one after another by the client based on the response from the previous API. I would say, create a single Lambda and just return the cumulative response to reduce the number of requests.您可以创建一个单独的 Lambda 来处理所有这些逻辑,或者创建由客户端根据前一个 API 的响应一个接一个地触发的 Lambda。我会说,创建一个单独的 Lambda 并只返回累积响应以减少请求的数量。 But again, this totally depends on the UI integration.但同样,这完全取决于 UI 集成。 If your screens demand separate API calls, then please, by all means create individual lambdas.如果您的屏幕需要单独的 API 调用,那么请务必创建单独的 lambda。

  3. This is not true.这不是真的。 We can have dynamic routes specified in the API Gateway.我们可以在 API 网关中指定动态路由。 You can easily set wildcards in your routes by using {variableName} while setting the routes in API Gateway.在 API 网关中设置路由时,您可以使用{variableName}轻松地在路由中设置通配符。

    GET /users/{userId} The userId will then be available at your disposal in the lambda function via event.pathParameters . GET /users/{userId}然后userId将通过event.pathParameters在 lambda function 中供您使用。

    GET /users/{userId}?a=x Similarly, you could even pass query strings and access them via event.queryStringParameters in code. GET /users/{userId}?a=x同样,您甚至可以传递查询字符串并通过代码中的event.queryStringParameters访问它们。 Have a look at working with routes .看看使用路由

Tutorial I would recommend for you:我会为你推荐的教程:

Tutorial: Build a CRUD API with Lambda and DynamoDB 教程:使用 Lambda 和 DynamoDB 构建 CRUD API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 无服务器 webapp 与 WSGI 服务器 - Python serverless webapp vs WSGI server 控制台与 CLI 创建的 AWS CloudWatch 警报之间的差异 - Differences between AWS CloudWatch alarms created by Console vs. CLI Express Amplify Serverless/GraphQL 与 Express 服务器端后端 - Express Amplify Serverless/GraphQL vs Express Server-Side backend “errorMessage”:在 AWS 无服务器上部署时“server.app.use 不是一个函数” - "errorMessage": "server.app.use is not a function" while deploying on AWS serverless Azure function 绑定与手动实例化 class - Azure function binding vs. manually instantiating class ScyllaDB:模式与无模式? - ScyllaDB: Schema vs. No Schema? 如何在 Twilio Serverless 中从 Function 调用 Function? - How to call a Function from a Function in Twilio Serverless? AWS Lambda function on Java with Serverless framework and GraalVM - AWS Lambda function on Java with Serverless framework and GraalVM 无服务器部署 - Function 未找到 - sls 部署 - Serverless deploy - Function not found - sls deploy 如何使用 Twilio CLI 删除无服务器 function? - How to delete a serverless function using Twilio CLI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM