第一個列子,當然是 Hello World
了… 下面使用 Python
, Go
, Java
分別實現…
首先準備好目錄:
└── helloworld
├── go
├── java
└── python
Python
使用CLI創建 function faas-cli new --lang python hello-world
, 會自動生成以下文件
└── helloworld
├── go
├── java
└── python
├── hello-world
│ ├── handler.py
│ └── requirements.txt #如果有dependency的話,就放進這裏
├── hello-world.yml
└── template #會有很多template,暫時先ignore
其中,handler.py
就是處理 request的 handler,這裏我們先實現 hello world的邏輯
def handle(req):
resp='Hello Rex, ' + req
print(resp)
return resp
之後使用配置文件hello-world.yml
來build func,
version: 1.0
provider:
name: openfaas #唯一的provider,value只能爲openfaas
gateway: http://<your-ip>:31112
functions:
hello-world:
lang: python
handler: ./hello-world
image: openfaas-hello-world:latest
運行faas-cli build -f ./hello-world.yml
之後,openfaas就將這個funct打包成一個新的image
$ docker image ls | grep hello
openfaas-hello-world latest 3 minutes ago 87.1MB
接下來就是部署和測試了,faas-cli deploy --image openfaas-hello-world --name hello-world-python
當然如果需要將新func upload到 Registry/Artifactory上,
faas-cli push -f ./hello-world.yml
,這之前需要配置secret
Golang
類似的,使用faas-cli new --lang go hello-world
創建新function;同樣的,openfaas會創建一下幾個文件
└── helloworld
├── go
│ ├── hello-world
│ │ └── handler.go
│ ├── hello-world.yml
│ └── template
添加handler實現
package function
import (
"fmt"
)
func Handle(req []byte) string {
return fmt.Sprintf("Hello Rex: %s", string(req))
}
部署並測試function
faas-cli build -f ./hello-world.yml
faas-cli deploy --image openfaas-hello-world-go --name hello-world-go
Java
同樣的套路,只不過java有幾個版本可以選,java8還是11之類的,faas-cli new --lang java8 hello-world
Java自動生成的目錄結構較Python和Go有很大不同,起碼使用gradle
build
java
├── hello-world
│ ├── build.gradle
│ ├── gradle
│ │ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
│ ├── settings.gradle
│ └── src
│ ├── main
│ │ └── java
│ │ └── com
│ │ └── openfaas
│ │ └── function
│ │ └── Handler.java
│ └── test
│ └── java
│ └── HandlerTest.java
├── hello-world.yml
└── template
直奔Handler,java
package com.openfaas.function;
import com.openfaas.model.IHandler;
import com.openfaas.model.IResponse;
import com.openfaas.model.IRequest;
import com.openfaas.model.Response;
public class Handler implements com.openfaas.model.IHandler {
public IResponse Handle(IRequest req) {
Response res = new Response();
res.setBody("Hello Rex, " + req.getBody());
return res;
}
}
之後就是部署並測試
faas-cli build -f ./hello-world.yml
faas-cli deploy --image openfaas-hello-world-java8 --name hello-world-java
這樣,基本算是hello world級別的瞭解了openfaas;那下一篇就深入的瞭解下openfaas
最後,Java主語言的我,在嘗試OpenFaaS
的HelloWorld的時候,很是不爽…
$ docker image ls | grep hello
openfaas-hello-world-go latest 25.1MB
openfaas-hello-world-python latest 87.1MB
openfaas-hello-world-java8 latest 141MB