knative eventing 體驗(yàn)

快速安裝

前提

需要本地安裝 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


cloudevent.png

體驗(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 查看日志

event-display.png

最終整個(gè)體驗(yàn)應(yīng)該如下


整體體驗(yàn)

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è)問題了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載麸澜,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者奏黑。
  • 序言:七十年代末熟史,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蹂匹,更是在濱河造成了極大的恐慌,老刑警劉巖忍啸,帶你破解...
    沈念sama閱讀 211,265評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異悄晃,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)妈橄,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評論 2 385
  • 文/潘曉璐 我一進(jìn)店門鸭巴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人溪椎,你說我怎么就攤上這事恬口。” “怎么了歉秫?”我有些...
    開封第一講書人閱讀 156,852評論 0 347
  • 文/不壞的土叔 我叫張陵养铸,是天一觀的道長。 經(jīng)常有香客問我兔甘,道長鳞滨,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,408評論 1 283
  • 正文 為了忘掉前任澡匪,我火速辦了婚禮褒链,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘荠瘪。我一直安慰自己,他們只是感情好哀墓,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評論 5 384
  • 文/花漫 我一把揭開白布篮绰。 她就那樣靜靜地躺著,像睡著了一般吠各。 火紅的嫁衣襯著肌膚如雪贾漏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,772評論 1 290
  • 那天梳码,我揣著相機(jī)與錄音伍掀,去河邊找鬼。 笑死蜜笤,一個(gè)胖子當(dāng)著我的面吹牛把兔,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播县好,決...
    沈念sama閱讀 38,921評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼聘惦,長吁一口氣:“原來是場噩夢啊……” “哼儒恋!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起诫尽,我...
    開封第一講書人閱讀 37,688評論 0 266
  • 序言:老撾萬榮一對情侶失蹤牧嫉,失蹤者是張志新(化名)和其女友劉穎减途,沒想到半個(gè)月后曹洽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,130評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡税产,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評論 2 325
  • 正文 我和宋清朗相戀三年辟拷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了阐斜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,617評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡隅俘,死狀恐怖到推,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情莉测,我是刑警寧澤,帶...
    沈念sama閱讀 34,276評論 4 329
  • 正文 年R本政府宣布忍抽,位于F島的核電站鸠项,受9級特大地震影響子姜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜哥捕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評論 3 312
  • 文/蒙蒙 一遥赚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧凫佛,春花似錦孕惜、人聲如沸晨炕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鲸郊。三九已至货邓,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間换况,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評論 1 265
  • 我被黑心中介騙來泰國打工舒裤, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留觉吭,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,315評論 2 360
  • 正文 我出身青樓伴鳖,卻偏偏與公主長得像徙硅,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子须肆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評論 2 348

推薦閱讀更多精彩內(nèi)容