跳至內容

阿里巴巴雲函數計算

阿里巴巴雲函數計算 是一項完全託管、事件驅動的計算服務。函數計算讓您可以專注於編寫和上傳程式碼,而無需管理伺服器等基礎設施。

1. 設定

serverless-devs 是一個開源且開放的無伺服器開發者平台,致力於為開發者提供強大的工具鏈系統。透過此平台,開發者不僅可以一鍵體驗多雲無伺服器產品並快速部署無伺服器專案,還可以管理無伺服器應用程式整個生命週期的專案,並將 serverless devs 與其他工具/平台簡單快速地結合,進一步提高研發、運營和維護效率。

安裝 serverless-devs CLI

sh
npm install @serverless-devs/s -g

新增 AK & SK 設定

sh
s config add
# Please select a provider: Alibaba Cloud (alibaba)
# Input your AccessKeyID & AccessKeySecret

2. Hello World

在新目錄中建立一個新專案

sh
npm init

新增所需的依賴項

sh
npm add hono @hono/node-server
npm add esbuild --save-dev

編輯 package.json 中的 scripts 區段

json
{
  "scripts": {
    "build": "esbuild --bundle --outfile=./dist/index.js --platform=node --target=node20 ./src/index.ts",
    "dev": "node ./dist/index.js",
    "deploy": "s deploy -y"
  }
}

編輯 src/index.ts

ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'

const REQUEST_ID_HEADER = 'x-fc-request-id'

const app = new Hono()

app.post('/initialize', (c) => {
  console.log(`RequestId: ${c.req.header(REQUEST_ID_HEADER)}`)
  return c.text('Initialize')
})

app.post('/invoke', (c) => {
  console.log(`RequestId: ${c.req.header(REQUEST_ID_HEADER)}`)
  return c.text('Invoke')
})

app.get('/', (c) => {
  return c.text('Hello from index!')
})

app.get('/hello', (c) => {
  return c.text('Hi!')
})

const port = 9000
console.log(`Server is running on port ${port}`)

serve({
  fetch: app.fetch,
  port,
})

編輯 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "skipLibCheck": true,
    "lib": ["ESNext"],
    "types": [],
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}

編輯 s.yaml

yaml
edition: 3.0.0
name: my-app
access: 'default'

vars:
  region: 'us-west-1'

resources:
  my_app:
    component: fc3
    props:
      region: ${vars.region}
      functionName: 'my-app'
      runtime: 'custom.debian10'
      description: 'hello world by Hono'
      timeout: 10
      memorySize: 512
      environmentVariables:
        PATH: >-
          /var/fc/lang/nodejs20/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin
        NODE_PATH: /opt/nodejs/node_modules
      cpu: 0.5
      diskSize: 512
      code: ./dist
      customRuntimeConfig:
        command:
          - node
          - index.js
        port: 9000
      triggers:
        - triggerConfig:
            methods:
              - GET
              - POST
              - PUT
              - DELETE
            authType: anonymous
            disableURLInternet: false
          triggerName: default
          description: ''
          qualifier: LATEST
          triggerType: http

3. 部署

最後,執行命令進行部署

sh
npm install # install dependencies
npm run build # Compile the TypeScript code to JavaScript
npm run deploy # Deploy the function to Alibaba Cloud Function Compute

根據 MIT 授權發布。