Blazor+Dapr+K8s微服務之事件發佈訂閱

我們要實現的是:在blazorweb服務中發佈一個事件,並傳遞事件參數,然後在serviceapi1服務中訂閱該事件,接收到blazorweb服務中發佈的事件和參數。

1         在blazorweb服務中發佈一個事件

在DaprTest1.Server項目的WeatherForecastController.cs文件中增加事件發佈API:

  [HttpPost(nameof(PublishTestEvent))]
        public async Task PublishTestEvent(TestEventModel eventModel)
        {
            await _daprClient.PublishEventAsync<TestEventModel>("pubsub", "TestEventName", eventModel);
        }

"TestEventModel"是自定義的事件消息類,"TestEventName"是事件的名稱,"pubsub" 是事件發佈訂閱的名稱,定義在“pubsub.yaml” 組件中:

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

這個組件中定義的發佈訂閱採用了Redis 的 Stream 特性,要注意舊版本的Redis是否支持Stream。

2         在serviceapi1服務中訂閱該事件

在DaprTest1.ServiceApi1項目中添加Dapr.AspNetCore包,該包實現了ASP.NET Core與Dapr的集成,例如依賴注入DaprClient對象,將事件訂閱發佈功能直接集成到 ASP.NET Core 模型綁定功能中等。

 

在DaprTest1.ServiceApi1項目的Startup.cs 文件增加事件訂閱相關代碼(注意綠色部分):

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers().AddDapr();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "DaprTest1.ServiceApi1", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DaprTest1.ServiceApi1 v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseCloudEvents();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapSubscribeHandler();
                endpoints.MapControllers();
            });
        }

在DaprTest1.ServiceApi1項目的WeatherForecastController文件增加事件訂閱API

  [Topic("pubsub", "TestEventName")]
        [HttpPost(nameof(SubscribleTestEvent))]
        public async Task SubscribleTestEvent(TestEventModel eventModel)
        {
             await Task.CompletedTask;
        }

[Topic("pubsub", "TestEventName")] 訂閱了"pubsub"訂閱名稱的TestEventName事件。

3         在Blazor項目中增加Blazor前端事件發佈菜單和頁面

@page "/pubsub"
@using DaprTest1.Shared
@using System.Text.Json
@inject HttpClient Http

<h1>發佈訂閱</h1>

<p>This component demonstrates publish and subscrible event.</p>

<p>編碼:<input type="text" @bind="eventModel.Code" />, 數量:<input type="text" @bind="eventModel.Amount" /></p>

<button class="btn btn-primary" @onclick="PublishEvent">發佈事件</button>



@code {
    private TestEventModel eventModel = new TestEventModel();
    private async Task PublishEvent() => await Http.PostAsJsonAsync<TestEventModel>("WeatherForecast/PublishTestEvent", eventModel);

}

 

4         事件發佈訂閱測試

和上一節一樣,我們先開啓每個微服務的SideCar,注意,因爲的SideCar 指定了狀態存儲的Redis,所以我們先要開啓Redis,不然SideCar會啓動失敗。確保每個微服務的SideCar都是運行狀態。

 

然後啓動兩個微服務,並訪問http://localhost:5000

 

在ServiceApi1服務的事件接收處設置好斷點,然後點擊“發佈事件”按鈕

 

可以看到,我們成功接收到了TestEventName事件和事件發佈的參數。

5         將Dapr的發佈訂閱組件修改爲RabbitMQ

通常情況下,我們會用RabbitMQ來支持事件的發佈和訂閱,我們將Dapr 發佈訂閱組件“pubsub.yaml”,修改爲如下內容即可:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: pubsub
spec:
  type: pubsub.rabbitmq
  version: v1
  metadata:
  - name: host
    value: "amqp://admin:******@localhost:5672"
  - name: durable
    value: true

 

相關代碼:iamxiaozhuang/dapr-test (github.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章