Serverless

2020-02-06 15:45 更新

Serverless

使用現(xiàn)有的 Fastify 應(yīng)用運行無服務(wù)器 (serverless) 應(yīng)用與 REST API。

讀者須知:

Fastify 并不是為無服務(wù)器環(huán)境準(zhǔn)備的。 Fastify 框架的設(shè)計初衷是輕松地實現(xiàn)一個傳統(tǒng)的 HTTP/S 服務(wù)器。 無服務(wù)器環(huán)境則與此不同。 因此,我們不保證在無服務(wù)器環(huán)境下,F(xiàn)astify 也能如預(yù)期般運轉(zhuǎn)。 盡管如此,參照本文中的示例,你仍然可以在無服務(wù)器環(huán)境中運行 Fastify。 再次提醒,無服務(wù)器環(huán)境不是 Fastify 的目標(biāo)所在,我們不會在這樣的集成情景下進(jìn)行測試。

AWS Lambda

以下是使用 Fastify 在 AWS Lambda 和 Amazon API Gateway 架構(gòu)上構(gòu)建無服務(wù)器 web 應(yīng)用/服務(wù)的示例。

注:使用 aws-lambda-fastify 僅是一種可行方案。

app.js

const fastify = require('fastify');

function init() {
  const app = fastify();
  app.get('/', (request, reply) => reply.send({ hello: 'world' }));
  return app;
}

if (require.main === module) {
  // 直接調(diào)用,即執(zhí)行 "node app"
  init().listen(3000, (err) => {
    if (err) console.error(err);
    console.log('server listening on 3000');
  });
} else {
  // 作為模塊引入 => 用于 aws lambda
  module.exports = init;
}

你可以簡單地把初始化代碼包裹于可選的 serverFactory 選項里。

當(dāng)執(zhí)行 lambda 函數(shù)時,我們不需要監(jiān)聽特定的端口,因此,在這個例子里我們只要導(dǎo)出 init 函數(shù)即可。 在 lambda.js 里,我們會用到它。

當(dāng)像往常一樣運行 Fastify 應(yīng)用, 比如執(zhí)行 node app.js 時 (可以用 require.main === module 來判斷), 你可以監(jiān)聽某個端口,如此便能本地運行應(yīng)用了。

lambda.js

const awsLambdaFastify = require('aws-lambda-fastify')
const init = require('./app');

const proxy = awsLambdaFastify(init())
// 或
// const proxy = awsLambdaFastify(init(), { binaryMimeTypes: ['application/octet-stream'] })

exports.handler = proxy;
// 或
// exports.handler = (event, context, callback) => proxy(event, context, callback);
// 或
// exports.handler = (event, context) => proxy(event, context);
// 或
// exports.handler = async (event, context) => proxy(event, context);

我們只需要引入 aws-lambda-fastify (請確保安裝了該依賴 npm i --save aws-lambda-fastify) 以及我們寫的 app.js,并使用 app 作為唯一參數(shù)調(diào)用導(dǎo)出的 awsLambdaFastify 函數(shù)。 以上步驟返回的 proxy 函數(shù)擁有正確的簽名,可作為 lambda 的處理函數(shù)。 如此,所有的請求事件 (API Gateway 的請求) 都會被代理到 aws-lambda-fastify 的 proxy 函數(shù)。

示例

你可以在這里找到使用 claudia.js 的可部署的例子。

注意事項

  • 你沒法操作 stream,因為 API Gateway 還不支持它。
  • API Gateway 的超時時間為 29 秒,請務(wù)必在此時限內(nèi)回復(fù)。

Google Cloud Run

與 AWS Lambda 和 Google Cloud Functions 不同,Google Cloud Run 是一個無服務(wù)器容器環(huán)境。它的首要目的是提供一個能運行任意容器的底層抽象 (infrastucture-abstracted) 的環(huán)境。因此,你能將 Fastify 部署在 Google Cloud Run 上,而且相比正常的寫法,只需要改動極少的代碼。

參照以下步驟部署 Google Cloud Run。如果你對 gcloud 還不熟悉,請看其入門文檔

調(diào)整 Fastfiy 服務(wù)器

為了讓 Fastify 能正確地在容器里監(jiān)聽請求,請確保設(shè)置了正確的端口與地址:

function build() {
  const fastify = Fastify({ trustProxy: true })
  return fastify
}

async function start() {
  // Google Cloud Run 會設(shè)置這一環(huán)境變量,
  // 因此,你可以使用它判斷程序是否運行在 Cloud Run 之中
  const IS_GOOGLE_CLOUD_RUN = process.env.K_SERVICE !== undefined

  // 監(jiān)聽 Cloud Run 提供的端口
  const port = process.env.PORT || 3000

  // 監(jiān)聽 Cloud Run 中所有的 IPV4 地址
  const address = IS_GOOGLE_CLOUD_RUN ? "0.0.0.0" : undefined

  try {
    const server = build()
    const address = await server.listen(port, address)
    console.log(`Listening on ${address}`)
  } catch (err) {
    console.error(err)
    process.exit(1)
  }
}

module.exports = build

if (require.main === module) {
  start()
}

添加 Dockerfile

你可以添加任意合法的 Dockerfile,用于打包運行 Node 程序。在 gcloud 官方文檔中,你能找到一份基本的 Dockerfile。

# 使用官方 Node.js 10 鏡像。
# https://hub.docker.com/_/node
FROM node:10

# 創(chuàng)建并切換到應(yīng)用目錄。
WORKDIR /usr/src/app

# 拷貝應(yīng)用依賴清單至容器鏡像。
# 使用通配符來確保 package.json 和 package-lock.json 均被復(fù)制。
# 獨立地拷貝這些文件,能防止代碼改變時重復(fù)執(zhí)行 npm install。
COPY package*.json ./

# 安裝生產(chǎn)環(huán)境依賴。
RUN npm install --only=production

# 復(fù)制本地代碼到容器鏡像。
COPY . .

# 啟動容器時運行服務(wù)。
CMD [ "npm", "start" ]

添加 .dockerignore

添加一份如下的 .dockerignore,可以將僅用于構(gòu)建的文件排除在容器之外 (能減小容器大小,加快構(gòu)建速度):

Dockerfile
README.md
node_modules
npm-debug.log

提交構(gòu)建

接下來,使用以下命令將你的應(yīng)用構(gòu)建成一個 Docker 鏡像 (將 PROJECT-ID 和 APP-NAME 替換為 Google 云平臺的項目 id 和 app 名稱):

gcloud builds submit --tag gcr.io/PROJECT-ID/APP-NAME

部署鏡像

鏡像構(gòu)建之后,使用如下命令部署它:

gcloud beta run deploy --image gcr.io/PROJECT-ID/APP-NAME --platform managed

如此,便能從 Google 云平臺提供的鏈接訪問你的應(yīng)用了。

Zeit Now

now 針對 Node.js 應(yīng)用提供了零配置部署方案。要使用 now,只需要如下配置你的 now.json 文件:

{
  "version": 2,
  "builds": [
    {
      "src": "api/serverless.js",
      "use": "@now/node",
      "config": {
        "helpers": false
      }
    }
  ],
  "routes": [
    { "src": "/.*", "dest": "/api/serverless.js"}
  ]
}

之后,寫一個 api/serverless.js 文件:

'use strict'
const build = require('./index')
const app = build()
module.exports = async function (req, res) {
  await app.ready()
  app.server.emit('request', req, res)
}

以及一個 api/index.js 文件:

'use strict'
const fastify = require('fastify')
function build () {
  const app = fastify({
    logger: true
  })
  app.get('/', async (req, res) => {
    const { name = 'World' } = req.query
    req.log.info({ name }, 'hello world!')
    return `Hello ${name}!`
  })
  return app
}
module.exports = build

要注意的是,你得在 package.json 中使用 Node 10:

  "engines": {
    "node": "10.x"
  },


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號