快速安裝
前提
需要本地安裝 k8s,可以嘗試使用 orbstack熬的,目前我使用的就是這個(gè)工具
為了更好的體驗(yàn) knative-eventing 的使用,還需要你本地有 golang 的環(huán)境以及 docker
安裝部署
通過以下命令安裝 knative eventing 相關(guān)組件
kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.12.0/eventing-crds.yaml
kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.12.0/eventing-core.yaml
kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.12.0/in-memory-channel.yaml
kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.12.0/mt-channel-broker.yaml
執(zhí)行 kubectl get po -A 你應(yīng)該可以看到如下信息
{19:55}~ ? kubectl get po -A
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system local-path-provisioner-957fdf8bc-ws7bh 1/1 Running 34 (2d1h ago) 64d
kube-system coredns-687f7d69ff-2pmhp 1/1 Running 21 (2d1h ago) 64d
knative-eventing eventing-webhook-68575ffb75-n8kcg 1/1 Running 0 16m
knative-eventing eventing-controller-5d4cd67984-djtgq 1/1 Running 0 16m
knative-eventing imc-dispatcher-7d9f7b5bc7-8p2g5 1/1 Running 0 14m
knative-eventing imc-controller-74bc76b745-v8lpw 1/1 Running 0 14m
knative-eventing mt-broker-filter-755d6d6454-c86kr 1/1 Running 0 10m
knative-eventing mt-broker-ingress-7bbdf9b6f8-9gp4r 1/1 Running 0 10m
knative-eventing mt-broker-controller-74895f6c47-gv4wh 1/1 Running 0 10m
快速體驗(yàn)
流程介紹
理解 knative eventing 的時(shí)候,總感覺很虛幻盒揉,因?yàn)槠渲袀鬟f的 cloudevent 是你很難看到摸到的兑徘,不過好在官方提供了一個(gè) helloworld-go 的項(xiàng)目,可以幫助我們更好的理解 kantive eventing
這個(gè)項(xiàng)目做的事情就是部署了一個(gè) deployment藕漱,這個(gè) deployment 可以接收 cloudevent 并且將接收到的 cloudevent 展示在日志中
為了讓大家更好的理解事件流動(dòng)的過程崭闲,這個(gè) deployment 還可以在接收到請求后,再構(gòu)造一個(gè)請求發(fā)送出去橄仍,發(fā)送出去的請求,也讓你可以在日志中看到
鏡像準(zhǔn)備
新建文件 helloworld.go虑粥,鍵入以下內(nèi)容鼎天,這個(gè)是主要工作的部分
做的事情就是接收事件,在日志中展示育勺,然后再構(gòu)造一個(gè)事件發(fā)送出去
在這里面使用 sdk-go 來處理 cloudevent 的信息
package main
import (
"context"
"log"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/uuid"
)
func receive(ctx context.Context, event cloudevents.Event) (*cloudevents.Event, cloudevents.Result) {
// Here is where your code to process the event will go.
// In this example we will log the event msg
log.Printf("Event received. \n%s\n", event)
data := &HelloWorld{}
if err := event.DataAs(data); err != nil {
log.Printf("Error while extracting cloudevent Data: %s\n", err.Error())
return nil, cloudevents.NewHTTPResult(400, "failed to convert data: %s", err)
}
log.Printf("Hello World Message from received event %q", data.Msg)
// Respond with another event (optional)
// This is optional and is intended to show how to respond back with another event after processing.
// The response will go back into the knative eventing system just like any other event
newEvent := cloudevents.NewEvent()
// Setting the ID here is not necessary. When using NewDefaultClient the ID is set
// automatically. We set the ID anyway so it appears in the log.
newEvent.SetID(uuid.New().String())
newEvent.SetSource("knative/eventing/samples/hello-world")
newEvent.SetType("dev.knative.samples.hifromknative")
if err := newEvent.SetData(cloudevents.ApplicationJSON, HiFromKnative{Msg: "Hi from helloworld-go app!"}); err != nil {
return nil, cloudevents.NewHTTPResult(500, "failed to set response data: %s", err)
}
log.Printf("Responding with event\n%s\n", newEvent)
return &newEvent, nil
}
func main() {
log.Print("Hello world sample started.")
c, err := cloudevents.NewDefaultClient()
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
log.Fatal(c.StartReceiver(context.Background(), receive))
}
新建文件 eventschemas.go涧至,鍵入以下內(nèi)容
這里的內(nèi)容很簡單桑包,只是發(fā)送和接收消息的結(jié)構(gòu)體
package main
// HelloWorld defines the Data of CloudEvent with type=dev.knative.samples.helloworld
type HelloWorld struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty"`
}
// HiFromKnative defines the Data of CloudEvent with type=dev.knative.samples.hifromknative
type HiFromKnative struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty"`
}
執(zhí)行如下命令哑了,創(chuàng)建 go.mod 文件
go mod init github.com/knative/docs/code-samples/serving/hello-world/helloworld-go
新建文件 Dockerfile,鍵入以下內(nèi)容
# Use the official Golang image to create a build artifact.
# This is based on Debian and sets the GOPATH to /go.
# https://hub.docker.com/_/golang
FROM golang:1.19 as builder
ARG TARGETOS
ARG TARGETARCH
# Copy local code to the container image.
WORKDIR /app
# Retrieve application dependencies using go modules.
# Allows container builds to reuse downloaded dependencies.
COPY go.* ./
RUN go mod download
# Copy local code to the container image.
COPY . ./
# Build the binary.
# -mod=readonly ensures immutable go.mod and go.sum in container builds.
RUN CGO_ENABLED=0 GOOS=linux GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -mod=readonly -v -o helloworld
# Use a Docker multi-stage build to create a lean production image.
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
FROM alpine:3
RUN apk add --no-cache ca-certificates
# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/helloworld /helloworld
# Run the web service on container startup.
CMD ["/helloworld"]
好了窄陡,此時(shí)我們可以先把鏡像構(gòu)建出來跳夭,鏡像構(gòu)建地址隨便们镜,只要是你能訪問到的地址即可
執(zhí)行以下命令,這樣構(gòu)建出來的鏡像就會(huì)上傳到了我的鏡像倉庫下
docker buildx build -t "yugougou/helloworld-go" --push .
k8s 資源準(zhǔn)備
新建 sample-app.yaml颈抚,鍵入以下內(nèi)容
如果你的鏡像地址不同嚼鹉,需要替換下 deployment 的鏡像地址
這里的資源包含如下幾個(gè)內(nèi)容
1、構(gòu)建出的鏡像對應(yīng)的 deployment 相關(guān)的 service
2雾鬼、用于事件轉(zhuǎn)發(fā)過濾的 broker 和 trigger
# Namespace for sample application
apiVersion: v1
kind: Namespace
metadata:
name: knative-samples
---
# A default broker
apiVersion: eventing.knative.dev/v1
kind: Broker
metadata:
name: default
namespace: knative-samples
annotations:
# Note: you can set the eventing.knative.dev/broker.class annotation to change the class of the broker.
# The default broker class is MTChannelBasedBroker, but Knative also supports use of the other class.
eventing.knative.dev/broker.class: MTChannelBasedBroker
spec: {}
---
# Knative Eventing Trigger to trigger the helloworld-go service
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
name: helloworld-go
namespace: knative-samples
spec:
broker: default
filter:
attributes:
type: dev.knative.samples.helloworld
source: dev.knative.samples/helloworldsource
subscriber:
ref:
apiVersion: v1
kind: Service
name: helloworld-go
---
# Helloworld-go app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: helloworld-go
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: helloworld-go
template:
metadata:
labels: *labels
spec:
containers:
- name: helloworld-go
image: docker.io/yugougou/helloworld-go
---
# Service that exposes helloworld-go app.
# This will be the subscriber for the Trigger
kind: Service
apiVersion: v1
metadata:
name: helloworld-go
namespace: knative-samples
spec:
selector:
app: helloworld-go
ports:
- protocol: TCP
port: 80
targetPort: 8080
執(zhí)行如下命令策菜,導(dǎo)入到 k8s 集群中
kubectl create -f sample-app.yaml
到目前為止,準(zhǔn)備工作已經(jīng)完成翠霍,我們可以開始體驗(yàn)事件傳遞的過程
體驗(yàn)事件接收
通過執(zhí)行 kubectl -n knative-samples get broker default
獲取到 broker 的地址
如下所示該例中為 http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default
NAME URL AGE READY REASON
default http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default 3d1h True
執(zhí)行 kubectl -n knative-samples run curl --image=radial/busyboxplus:curl -it
進(jìn)入 pod 中執(zhí)行如下命令(地址記得換成上面獲取到的 broker 中存儲(chǔ)的地址) 發(fā)送事件到我們部署的 helloworld-go
中
curl -v "http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default" \
-X POST \
-H "Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79" \
-H "Ce-Specversion: 1.0" \
-H "Ce-Type: dev.knative.samples.helloworld" \
-H "Ce-Source: dev.knative.samples/helloworldsource" \
-H "Content-Type: application/json" \
-d '{"msg":"Hello World from the curl pod."}'
執(zhí)行如下命令寒匙,去查看我們部署的 helloworld-go
中的日志
kubectl --namespace knative-samples logs -l app=helloworld-go --tail=50
如下圖所示躏将,我們可以看到 hellowrold-go 已經(jīng)接收到了 cloudevent 并且也嘗試的往外發(fā)送了一個(gè) cloudevent
體驗(yàn)事件發(fā)送
helloworld-go 發(fā)送的 cloudevent祸憋,我們又應(yīng)該怎么來驗(yàn)證呢,怎么知道它發(fā)出的 cloudevent 是生效了還是沒生效呢
當(dāng)然有辦法蚯窥,把以下內(nèi)容 apply 到集群后拦赠,使用 curl 的 pod 來發(fā)送 cloudevent,通過查看 event-display 的日志來驗(yàn)證是否接收到了發(fā)送的 cloudevent
# event-display app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: event-display
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: event-display
template:
metadata:
labels: *labels
spec:
containers:
- name: helloworld-go
# Source code: https://github.com/knative/eventing/tree/main/cmd/event_display
image: gcr.io/knative-releases/knative.dev/eventing/cmd/event_display
---
# Service that exposes event-display app.
# This will be the subscriber for the Trigger
kind: Service
apiVersion: v1
metadata:
name: event-display
namespace: knative-samples
spec:
selector:
app: event-display
ports:
- protocol: TCP
port: 80
targetPort: 8080
---
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
name: event-display
namespace: knative-samples
spec:
broker: default
filter:
attributes:
type: dev.knative.samples.hifromknative
source: knative/eventing/samples/hello-world
subscriber:
ref:
apiVersion: v1
kind: Service
name: event-display
執(zhí)行 kubectl logs -f -n knative-samples deploy/event-display
查看日志
最終整個(gè)體驗(yàn)應(yīng)該如下
Respect
knative eventing 安裝
通過 helloworld-go 理解 eventing
其他
在看 helloworld-go README.md 的時(shí)候,發(fā)現(xiàn) README.md 里面的代碼示例是完全錯(cuò)誤的,于是提了個(gè)相關(guān)的 PR牡辽,這里大家需要注意一下分辨,等 PR 合并后應(yīng)該就沒有這個(gè)問題了