创建**App.Shared**类库,并引入Volo.Abp.EventBus。引入这个库是因为要使用EventNameAttribute,设置事件名称,如果不声明,事件名称将是包含命名空间的事件类的全名。相当于RabbitMq里面的RoutingKey。
using System;using Volo.Abp.EventBus;namespace App.Shared{[Serializable][EventName("Test.App1ToApp2")]public class App1ToApp2Eto{public string Message { get; set; }public App1ToApp2Eto() { }public App1ToApp2Eto(string message){Message = message;}}}
using System;using Volo.Abp.EventBus;namespace App.Shared{[Serializable][EventName("Test.App2ToApp1")]public class App2ToApp1Eto{public string Message { get; set; }public App2ToApp1Eto() { }public App2ToApp1Eto(string message){Message = message;}}}
创建**App1**控制台项目。
引入包Volo.Abp.EventBus.RabbitMQ和Volo.Abp.Autofac。
创建启动Module
using Volo.Abp.Autofac;using Volo.Abp.EventBus.RabbitMq;using Volo.Abp.Modularity;using Volo.Abp.RabbitMQ;namespace App1;[DependsOn(typeof(AbpAutofacModule),typeof(AbpEventBusRabbitMqModule))]public class App1Module : AbpModule{public override void ConfigureServices(ServiceConfigurationContext context){// 如果不配置默认本地Configure<AbpRabbitMqOptions>(options =>{options.Connections.Default.UserName = "UserName";options.Connections.Default.Password = "Password";options.Connections.Default.HostName = "HostName";options.Connections.Default.Port = 5672;});Configure<AbpRabbitMqEventBusOptions>(options =>{options.ClientName = "App1";options.ExchangeName = "TestMessageing";});}}
如果不设置AbpRabbitMqOptions,则会走默认的本地配置,账号也是默认的guest账号。
在Program类中设置启动项。
using Microsoft.Extensions.DependencyInjection;using Volo.Abp;namespace App1;internal class Program{static async Task Main(string[] args){using var app = AbpApplicationFactory.Create<App1Module>(options =>{options.UseAutofac();});await app.InitializeAsync();var service = app.ServiceProvider.GetRequiredService<App1MessagingService>();await service.RunAsync();await app.ShutdownAsync();}}
这里的App1MessagingService类,是利用控制台,接受输入的消息,进行发送事件。
using App.Shared;using Volo.Abp.DependencyInjection;using Volo.Abp.EventBus.Distributed;namespace App1;public class App1MessagingService : ITransientDependency{private readonly IDistributedEventBus _distributedEventBus;public App1MessagingService(IDistributedEventBus distributedEventBus){_distributedEventBus = distributedEventBus;}public async Task RunAsync(){string message;do{Console.Write("App1请发送消息:");message = Console.ReadLine();await _distributedEventBus.PublishAsync(new App1ToApp2Eto(message));} while (message != "exit");}}
有发送就有接收,**App1**项目接收**App2**发送的事件。
using App.Shared;using Volo.Abp.DependencyInjection;using Volo.Abp.EventBus.Distributed;namespace App1;public class App1EventHandler : IDistributedEventHandler<App2ToApp1Eto>, ITransientDependency{public Task HandleEventAsync(App2ToApp1Eto eventData){Console.WriteLine();Console.WriteLine("App1收到消息:" + eventData.Message);return Task.CompletedTask;}}
创建App2和App1大体一样。
整体项目结构。
将两个项目启动,并测试。


