微服務實踐k8s&dapr開發部署實驗(3)訂閱釋出

shiningrise發表於2024-05-28

自託管模式執行dapr

新建訂閱webapi專案,取名為backend

專案增加docker支援,取消https支援

修改Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

//訂閱需要用到以下方法
app.UseCloudEvents();
app.MapSubscribeHandler();

//if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

修改WeatherForecastController.cs

using Dapr;
using Microsoft.AspNetCore.Mvc;

namespace backend.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpPost("TestSub")]
        [Topic("pubsub", "deathStarStatus")]
        public object TestSub([FromBody]string message)
        {
            Console.WriteLine($"TestSub deathStarStatus {message}");

            return new { message = "TestSub deathStarStatus" };
        }
        
    }
}

Topic 就是確定接收的主題

修改launchSettings.json

將applicationUrl引數改為"http://localhost:5001"

在backend專案根目錄下執行

dapr run --app-id backend --app-port 5001 dotnet run 

新建釋出事件webapi專案,取名為front

專案增加docker支援,取消https支援

修改Program.cs,增加dapr支援

修改WeatherForecastController.cs

using Dapr.Client;
using Microsoft.AspNetCore.Mvc;

namespace front.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly DaprClient _daprClient;

        public WeatherForecastController(DaprClient daprClient)
        {
            _daprClient = daprClient;
        }

        [HttpPost("TestPub")]
        public async Task TestPub([FromBody]string msg)
        {
            try
            {
                await _daprClient.PublishEventAsync<string>("pubsub", "deathStarStatus", msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

_daprClient.PublishEventAsync("pubsub", "deathStarStatus", msg); 此方法就是釋出訂閱

修改launchSettings.json檔案,將"applicationUrl"改為 "http://localhost:5002"

在front專案根目錄執行

dapr run --app-id front --app-port 5002 dotnet run 

命令列釋出訂閱

dapr publish --publish-app-id front --pubsub pubsub --topic deathStarStatus --data "hello"

backend控制檯會顯示下面訊息

網頁釋出訂閱

訪問front網站,Swagger UI

執行TestPub後,backend專案控制檯會顯示接受到訂閱訊息

k8s模式執行dapr

#初始化dapr叢集
dapr uninstall --all
docker rm -f backend front
dapr init -k

構建docker映象

docker build -t daprbackend:v2 -f backend/Dockerfile .
docker build -t daprfrontend:v2 -f front/Dockerfile .

執行k8s專案

kubectl apply -f k8s/dapr-backend.yaml
kubectl apply -f k8s/dapr-front.yaml

dapr-backend.yaml

kind: Deployment
apiVersion: apps/v1
metadata:
  name: dapr-deploy-backend
  labels:
    service: backend
spec:
  replicas: 1
  selector:
    matchLabels:
       service: backend
  template:
    metadata:
      labels:
        service: backend
      annotations:
        dapr.io/enabled: "true"
        dapr.io/app-id: "backend" #這裡要注意app-id要與front呼叫的名稱要一致
        dapr.io/app-port: "8080"
        #dapr.io/config: "dapr-config"
    spec:
      containers:
        - name: daprbackend
          image: daprbackend:v2
          imagePullPolicy: Never
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: daprbackend
  labels:
    service: backend
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30003
      protocol: TCP
      name: http
    - port: 50001
      targetPort: 50001
      nodePort: 30042
      protocol: TCP
      name: dapr-grpc
  selector:
    service: backend

dapr-front.yaml

kind: Deployment
apiVersion: apps/v1
metadata:
  name: dapr-deploy-front
  labels:
    service: front
spec:
  replicas: 1
  selector:
    matchLabels:
       service: front
  template:
    metadata:
      labels:
        service: front
      annotations:
        dapr.io/enabled: "true"
        dapr.io/app-id: "front"
        dapr.io/app-port: "8080"
        #dapr.io/config: "dapr-config"
    spec:
      containers:
        - name: daprfrontend
          image:  daprfrontend:v2
          imagePullPolicy: Never
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: daprfrontend
  labels:
    service: front
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30004
      protocol: TCP
      name: http
    - port: 50001
      targetPort: 50001
      nodePort: 30041
      protocol: TCP
      name: dapr-grpc
  selector:
    service: front

執行釋出端專案

訪問http://127.0.0.1:30004/swagger/index.html

執行TestPub,

終端會顯示以下錯誤,原因是pubsub元件沒執行

執行pubsub元件

kubectl apply -f redis.yaml
kubectl apply -f pubsub.yaml

redis.yaml檔案

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: redis
    version: v1
  name: redis
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redis:6-alpine
          imagePullPolicy: IfNotPresent
          ports:
          - containerPort: 6379

---

apiVersion: v1
kind: Service
metadata:
  labels:
    app: redis
  name: redis
spec:
  type: NodePort
  ports:
  - name: "data"
    port: 6379
    targetPort: 6379
  selector:
    app: redis

pubsub.yaml檔案

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: pubsub
spec:
  type: pubsub.redis
  version: v1
  metadata:
  - name: redisHost
    value: redis:6379
  - name: redisPassword
    value: ""

重新執行釋出於訂閱程式

kubectl delete -f k8s/dapr-front.yaml
kubectl delete -f k8s/dapr-backend.yaml

kubectl apply -f k8s/dapr-front.yaml
kubectl apply -f k8s/dapr-backend.yaml

驗證實驗成功

訪問 http://127.0.0.1:30004/swagger/index.html

檢視訂閱端的日誌,收到資訊“wxy",就表示實驗成功

常用命令

dapr run --app-id backend --app-port 5001 dotnet run 
dapr run --app-id front --app-port 5002 dotnet run 
dapr publish --publish-app-id front --pubsub pubsub --topic deathStarStatus --data "hello"

::kubectl delete all --all
::dapr uninstall --all

dapr uninstall --all
docker rm -f backend front
dapr init -k

docker build -t daprbackend -f backend/Dockerfile .
docker build -t daprfrontend -f front/Dockerfile .

Dapr uninstall --all
dapr init -k
kubectl apply -f k8s/dapr-backend.yaml
kubectl apply -f k8s/dapr-front.yaml

pause

參考文章

  • 透過Dapr實現一個簡單的基於.net的微服務電商系統(四)——一步一步教你如何擼Dapr之訂閱釋出
  • 手把手教你學Dapr - 6. 釋出訂閱
  • Dapr Pub-Sub

文章原始碼下載

點選下載

作者

吳曉陽,微訊號:shiningrise,email:shiningrise@qq.com

相關文章