AWS通過lambda實現後端服務的serverless部署。阿里雲對標的函數計算也可以實現相應的功能。
預備知識:
- nodejs
- express
- 阿里雲函數計算
- 阿里雲API網關
實現:
一、 安裝依賴
首先我們需要初始化一個工程。
npm init
npm install express alicloud-serverless-express
二、
安裝完依賴後,我們需要開始編寫一個helloworld 代碼。
首先我們需要一個express實例
// app.js
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
//app.listen(8080);
module.exports = app;
然後我們需要通過alicloud-serverless-express
來啓動express server。其中exports.handler
是函數計算的入口函數。詳見 Nodejs 函數入口。
// index.js
const alicloudServerlessExpress = require('alicloud-serverless-express');
const app = require('./app');
const server = alicloudServerlessExpress.createServer(app);
exports.handler = (event, context, callback) =>{
try{
event = JSON.parse(event.toString());
}catch(err){
console.log('local event')
}
alicloudServerlessExpress.proxy(server, event, callback);
}
在阿里雲的serverless express實現過程中。我們使用API 網關(以函數計算作爲API網關後端服務)暴露外部API, 使用函數計算命令行工具 fun實現API 網關和函數計算的一鍵部署。
三、 fun 部署
首先,需要編寫template.yml
:
template.yml:
Resources:
fc-demo:
Type: 'Aliyun::Serverless::Service'
Properties:
Description: 'fc service '
feedback:
Type: 'Aliyun::Serverless::Function'
Properties:
Handler: index.handler
Runtime: nodejs8
CodeUri: './'
Timeout: 60
apigateway_demo:
Type: 'Aliyun::Serverless::Api'
Properties:
StageName: RELEASE
DefinitionBody:
'/':
get:
x-aliyun-apigateway-api-name: demo
x-aliyun-apigateway-description: api gateway of demo
x-aliyun-apigateway-request-config:
requestMode: "PASSTHROUGH"
requestProtocol: "http,https"
x-aliyun-apigateway-visibility: PUBLIC
x-aliyun-apigateway-fc:
arn: acs:fc:::services/${fc-demo.Arn}/functions/${feedback.Arn}/
timeout: 3000
注意,這裏的template.yml
的存放路徑和函數計算的CodeUri: './'
是具有直接聯繫的,當CodeUri
爲'./'
時,需要將template.yml
和index.js
放在同級目錄下。
最後,在template.yml
所在的目錄下執行:
fun deploy