Serverless
# Serverless
持续完善
参考:https://blog.csdn.net/CharlesYooSky/article/details/103021510
- 按量付费
- 弹性伸缩
- 无需运维
- 开发简单
- 降低风险
- 易于扩展
历史:物理机时代 -> 虚拟机时代 -> 容器时代 -> Serverless 时代
# IaaS、PaaS、SaaS、FaaS、BaaS
# IaaS
Infrastructure as a Service(基础设施即服务)
# PaaS
Platform as a Service(平台即服务)
# SaaS
Software as a Service(软件即服务)
# FaaS
Function as a service(函数即服务)
# BaaS
Backend as a Service(后端即服务)
# 简介
- Serverless 的应用基本组成单位是函数,函数之间相互独立,因此 Serverless 能提高应用稳定性
- 广义的 Serverless 是构建和运行软件时不需要关心服务器的一种架构思想
- 狭义的 Serverless 是 FaaS 和 BaaS 的组合

① 开发者编写代码
② 把代码上传到函数计算上,上传的方式有通过 API 或者 SDK 上传,也可以通过控制台页面上传
③ 通过 API&SDK 来触发函数计算执行,同样也可以通过云产品的事件源来触发函数计算执行。
④ 函数计算在执行过程中,会根据用户请求量动态扩容函数计算来保证请求峰值的执行,这个过程对用户是透明无感知的。
⑤ 函数执行结束后,可以通过账单来查看执行费用,根据函数的实际执行时间按量计费。
# 优化
核心就是减少冷启动
下载代码 | 启动运行环境 | 执行初始化代码 | 执行入口函数 |
---|---|---|---|
完全冷启动 | 完全冷启动 | 部分冷启动 | 热启动 |
函数第一次执行的时候一定是冷启动
但后面的请求不一定都是热启动
这与触发函数执行的事件是串行还是并行有关
- 避免函数冷启动
- 对函数进行预热:在真实请求到来之前对函数发起请求,是函数提前初始化
- 使用预留资源
- 减小代码体积
- 避免引入不必要的依赖
- 不要加载不需要的代码
- 对 SDK 进行精简
- 对代码进行压缩
- 提升函数吞吐量
- 选择合适的编程语言
# 使用
以阿里云函数计算为例
- 开通功能:https://www.aliyun.com/product/fc?spm=5176.cnfnf.J_8058803260.121.2e291ea8S1XE81 (opens new window)
- 创建函数:
- 以 http 函数为例
- 入口:
index.exports.handler
- 执行请求:
curl https://xxxxxxxxxx.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/helloworld/sayhello/
var getRawBody = require('raw-body')
var getFormBody = require('body/form')
var body = require('body')
/*
To enable the initializer feature (https://help.aliyun.com/document_detail/156876.html)
please implement the initializer function as below:
exports.initializer = (context, callback) => {
console.log('initializing');
callback(null, '');
};
*/
exports.handler = (req, resp, context) => {
console.log('hello world')
var params = {
path: req.path,
queries: req.queries,
headers: req.headers,
method: req.method,
requestURI: req.url,
clientIP: req.clientIP,
}
getRawBody(req, function(err, body) {
for (var key in req.queries) {
var value = req.queries[key]
resp.setHeader(key, value)
}
params.body = body.toString()
resp.send(JSON.stringify(params, null, ' '))
})
/*
getFormBody(req, function(err, formBody) {
for (var key in req.queries) {
var value = req.queries[key];
resp.setHeader(key, value);
}
params.body = formBody;
console.log(formBody);
resp.send(JSON.stringify(params));
});
*/
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

注意:http 函数服务,不要用浏览器直接去请求,虽然也是发起 get 请求,但是会被浏览器当成附件下载
# 优化应用成本
- 提升函数性能
- serverless 应用是按执行次数和执行时消耗的内存等资源计费,函数性能越高,执行时间越短,成本越低
- 为函数设置超时时间
- 为了避免函数因异常而无限运行
- 选择合适的云服务
- 选择合适的计费方式
- 按量付费和预付费
- 关注 Fass 和 Bass 等云服务的总成本
上次更新: 2021/04/03, 17:32:58