编写完成后,可以先在本地测试该服务是否启动成功,通过安装在项目中的 ts-node 命令来运行上述代码:
# 启动 HTTP 服务
$ ./node_modules/.bin/ts-node server.ts
启动后,在另一个终端中使用 curl 命令测试:
$ curl 0.0.0.0:9000 -X POST -d “hello world” -H “x-fc-request-id:123”
hello world
若服务已正常启动,说明它可以在接收 HTTP 请求后处理业务逻辑,然后将处理结果再以 HTTP 响应的形式返回给 FaaS 平台。
2.创建一个启动目标 Server 的可执行文件 bootstrap
函数计算冷启动 Custom Runtime 时,会默认调用 bootstrap 文件启动自定义的 HTTP Server。然后这个 HTTP Server 接管了函数计算系统的所有请求。
-
bootstrap 是运行时入口引导程序文件,它会告诉 FaaS 如何启动你的自定义运行时。Custom Runtime 加载函数时会固定检索 bootstrap 同名文件,并执行该程序来启动 Custom Runtime 运行时。
-
bootstrap 需具备 777 或 755 可执行权限
-
如果是 shell 脚本,一定要添加
#!/bin/bash
创建 bootstrap 文件如下:
#!/bin/bash
./node_modules/.bin/ts-node server.ts
3.编写资源配置文件 template.yaml
在当前目录下编写一份用于部署到函数计算的资源配置文件 template.yaml:
ROSTemplateFormatVersion: ‘2015-09-01’
Transform: ‘Aliyun::Serverless-2018-04-03’
Resources:
custom-runtime: # 服务名称
Type: ‘Aliyun::Serverless::Service’
Properties:
Description: ‘helloworld’
custom-runtime-ts: # 函数名称
Type: ‘Aliyun::Serverless::Function’
Properties:
Handler: index.handler # Handler 在此时没有实质意义,填写任意的一个满足函数计算 Handler 字符集约束的字符串即可, 例如 index.handler
Runtime: custom # custom 代表自定义运行时
MemorySize: 512
CodeUri: ‘./’
4.部署、调用测试、完成
(1)使用 fun deploy -y
命令将我们的自定义运行时和业务逻辑代码所有资源部署到阿里云。
(2)使用命令调用部署函数,验证
$ fun invoke -e “hello,my custom runtime”
看到成功输出,就代表我们的 Custom Runtime 大功告成了!它可以直接运行我们写的 TS 代码了。
实现 Custo