Skip to content

OpenFaaS — 函数即服务

什么是 OpenFaaS

OpenFaaS 是 K8s 上的 FaaS(Function as a Service)平台,将任何语言的函数打包为容器运行。

安装

bash
# 安装 faas-cli
curl -sSL https://cli.openfaas.com | sudo sh

# 使用 Helm 安装 OpenFaaS
helm repo add openfaas https://openfaas.github.io/faas-netes/
helm install openfaas openfaas/openfaas \
  --namespace openfaas \
  --create-namespace \
  --set functionNamespace=openfaas-fn \
  --set generateBasicAuth=true

# 获取密码
PASSWORD=$(kubectl -n openfaas get secret basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 -d)
echo $PASSWORD

# 登录
kubectl port-forward -n openfaas svc/gateway 8080:8080 &
faas-cli login --username admin --password $PASSWORD

创建函数

bash
# 创建 Go 函数
faas-cli new my-function --lang go

# 目录结构
my-function/
├── handler.go
└── go.mod
my-function.yml
go
// handler.go
package function

import (
    "fmt"
    "net/http"
)

func Handle(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello from OpenFaaS!")
}
yaml
# my-function.yml
version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:8080

functions:
  my-function:
    lang: go
    handler: ./my-function
    image: my-registry/my-function:latest
    environment:
      LOG_LEVEL: info
    limits:
      cpu: 200m
      memory: 256Mi
    requests:
      cpu: 50m
      memory: 64Mi
    labels:
      com.openfaas.scale.min: "1"
      com.openfaas.scale.max: "10"
      com.openfaas.scale.factor: "20"

部署和调用

bash
# 构建、推送、部署
faas-cli up -f my-function.yml

# 调用函数
faas-cli invoke my-function <<< "Hello"
curl http://localhost:8080/function/my-function -d "Hello"

# 查看函数列表
faas-cli list

# 查看函数日志
faas-cli logs my-function

异步调用

bash
# 异步调用(立即返回,后台执行)
curl -X POST http://localhost:8080/async-function/my-function \
  -H "X-Callback-Url: http://my-callback-service/result" \
  -d "input data"

本站内容由 褚成志 整理编写,仅供学习参考