首页 > 其他分享 >微服务实践k8s&dapr开发部署实验(3)订阅发布

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

时间:2024-05-28 15:57:44浏览次数:22  
标签:订阅 name -- app dapr front k8s backend

自托管模式运行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:[email protected]

标签:订阅,name,--,app,dapr,front,k8s,backend
From: https://www.cnblogs.com/shiningrise/p/18218164

相关文章

  • Kubernetes(k8s) v1.30.1 本地集群部署 安装metallb 支持LoadBalancer 生产环境 推荐
    1 metallb安装参考:Kubernetes(k8s)v1.30.1本地集群部署默认不支持LoadBalancermetallb来解决-CSDN博客2 删除Layer2模式配置kubectldelete-fIPAddressPool.yamlkubectldelete-fL2Advertisement.yamlkubectldelete-fdiscuz-srv.yaml3配置k8sMeta......
  • k8s核心组件
    k8s核心组件KubernetesAPIServer由于APIServer是Kubernetes集群数据的唯一访问入口,因此安全性与高性能成为APIServer设计和实现的两大核心目标。通过采用HTTPS安全传输通道与CA签名数字证书强制双向认证的方式,APIServer的安全性得以保障。此外,为了更细粒度地控制用户或应用......
  • 云原生周刊:K8s 上的 gRPC 名称解析和负载平衡
    开源项目推荐KrakenKraken是一个基于P2P的Docker注册表,专注于可扩展性和可用性。它专为混合云环境中的Docker镜像管理、复制和分发而设计。借助可插拔的后端支持,Kraken可以轻松集成到现有的Docker注册表设置中作为分发层。E2EFramework这个项目是一个专门用于Kube......
  • 【保姆级教程】如何订阅patreon?patreon订阅需要银行卡?patreon虚拟信用卡购买支付教程
    1.引言什么是Patreon:Patreon是一个在线平台,允许内容创作者通过订阅服务的模式从他们的粉丝那里直接获得资金或者打赏。这个平台支持各种创作者,包括艺术家、音乐家、作家、视频制作人等。他们通过定期发布独家内容,然后粉丝进行付费或者免费订阅。目的:本教程旨在帮助大家......
  • k8s配置文件方式部署pod
    1.配置文件方式部署pod1.1 生成yaml文件#1.项目尝试启动,生成项目启动yaml文件kubectlcreatedeploymentspringboot-k8s--image=38-springboot-k8s-1.0.0-jar--dry-run-oyaml>deploy.yaml 1.2 修改yaml文件,配置从本地拉取镜像apiVersion:apps/v1kind:Depl......
  • k8s 怎么精准获取deployment关联的pods?
    标签获取我们获取那些pods属于某个deployment时最先想到的可能是通过标签获取,其实这个是不准确的。因为标签并不是唯一的,也就是说不同deployment其实是能有相同标签的。replicaSets获取deployment的产生pod流程如下:deployment->replicaSets->pod。deployment先产生replic......
  • 通过apisix访问k8s的service示例
    kind:IngressapiVersion:networking.k8s.io/v1metadata:labels:app:test-webname:test-webnamespace:testannotations:k8s.apisix.apache.org/enable-websocket:"true"kubernetes.io/ingress.class:apisixkubernetes.io/p......
  • 【重要】国内使用Onlyfans只看这一篇就够了!【最新】史上最详细OnlyFans订阅教程!【最快
    常见问题Q:Onlyfans是什么?A:是一个开放性创作分享平台,但是也充斥着成*人内容,这方面用户量堪比P某站Q:Onlyfans在哪里用?A:只需要访问Onlyfans官网就可以使用Onlyfans了。Q:onlyfans为什么首页啥也没有?A:因为onlyfans注重保护用户隐私,如果你想看到某个用户的推文,你需要订......
  • k8s练习--通过NFS+PV+PVC+POD,部署一个MySQL服务,并将MySQL的数据进行持久化存储
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、实验环境二、具体步骤1.准备存储设备:这里使用的是NFS2.现在部署一个MySQL服务,并且将MySQL的数据进行持久化存储。(1)创建PV,PVC(2)部署MySQL(3)在MySQL数据库中添加数据(4)模拟MySQ服务器节点故障......
  • KubeSphere系列---【离线安装kubeSphere时报错:failed: [k8s_node02] failed to conne
    1.报错信息[root@k8s_masterkubesphere-3.4.1-1.23.15-offline-package]#./kkinitregistry-fconfig-sample.yaml-akubesphere.tar.gz_______||//||||//||//__||_____||//_____......