前端技术

【Serverless 极速指南】Hello World

2019-08-19  本文已影响17人  一俢

Serverless 是当前较为先进的互联网架构,它被称作无服务器服务,并不是它不需要服务器了,而是作为应用服务提供者或者工程师,对运维不用太关注,而是更多的关注服务本身。它将是云服务提供商的又一次升级,将服务作为产品卖给应用服务提供商(或者开发人员),应用服务端将彻底(可能太绝对了)的告别机器运维,专心为用户提供良好的应用服务体验。

这篇文章你会学习到:

创建 AWS IAM

首先你需要有 AWS(Amazon Web Service 亚马逊云服务) 账户,这个过程大家自己去完成,跟注册一个网站的用户过程差不多。进入网站控制台后,搜索服务 IAM 服务(Identity and Access Management 认证权限管理),在你的 AWS 账户中 添加用户 中增加用户:

为什么要创建 IAM 用户 呢?因为我们需要用程序的方式来访问 AWS Serverless 的相关服务,例如:Lambda、S3、API Gateway、EC2 等等,只有通过这些服务,我们才能够搭建起自己的 Serverless。

安装 Serverless

这个步骤是我们的家常便饭:

yarn global add serverless
# Or
npm install -g serverless
serverless -v
1.49.0 (Enterprise Plugin: 1.3.4, Platform SDK: 2.1.0)

你可以通过 serverless -h 命令来看看相关帮助。

配置证书

还记得之前在创建 IAM 用户 时生成的 访问密钥 ID私有访问密钥 吗?这个时候要用到了,它时让你去访问 AWS 相关服务的钥匙:

erverless config credentials --provider aws --key AWS_ACCESS_KEY_ID --secret AWS_SECRET_ACCESS_KEY

通过 cat ~/.aws/credentials 命令来验证自己配置是否正确:

cat ~/.aws/credentials
[default]
aws_access_key_id=***********
aws_secret_access_key=***********

创建项目

接下来我们通过 serverless create --template aws-nodejs --path hello-world Serverless 模版会帮你创建一个项目:

$ serverless create --template aws-nodejs --path hello-world
Serverless: Generating boilerplate...
Serverless: Generating boilerplate in "/Users/lijia/Desktop/trip/hello-world"
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.49.0
 -------'

Serverless: Successfully generated boilerplate for template: "aws-nodejs"

部署到 AWS

进入到 hello-world ,运行命令 serverless deploy -v 静静等待:

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Service files not changed. Skipping deployment...
Service Information
service: hello-world
stage: dev
region: cn-north-1
stack: hello-world-dev
resources: 5
api keys:
  None
endpoints:
  None
functions:
  hello: hello-world-dev-hello
layers:
  None

Stack Outputs
HelloLambdaFunctionQualifiedArn: arn:aws-cn:lambda:cn-north-1:263001305225:function:hello-world-dev-hello:1
ServerlessDeploymentBucketName: hello-world-dev-serverlessdeploymentbucket-th8xm19prb82

Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.

这样你可以在 AWS 的 Lambda 管理界面中找点自己的那个服务。

调用

通过命令 sls invoke -f hello 可以调用到你刚刚部署的服务:

sls invoke -f hello
{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Hello world\"\n}"
}

当然,这个服务还不算完整的服务,它需要公布出 HTTP 服务,这个我们会在后面的文章中介绍。

〖坚持的一俢〗

上一篇 下一篇

猜你喜欢

热点阅读