微服务实践k8s&dapr开发部署实验(3)订阅发布

自托管模式运行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

参考文章

文章源码下载

待上传

作者

吴晓阳,微信号:shiningrise,email:shiningrise@qq.com