我将在Request / Response模式下使用RabbitMQ和MassTransit在.Net Core中实现我的应用。
这是接收方的代码(它接收用户名和密码,然后将用户名和提供者密钥发送给客户端):
//BusConfiguration.cs
public static IBusControl ConfigureBus(
Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> registrationAction = null)
{
return Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(RabbitMqConstants.RabbitMqUri), hst =>
{
hst.Username(RabbitMqConstants.UserName);
hst.Password(RabbitMqConstants.Password);
});
registrationAction?.Invoke(cfg, host);
});
}
public void ConfigureBus()
{
bus = BusConfigurator.ConfigureBus((cfg, host) =>
{
cfg.ReceiveEndpoint(host, RabbitMqConstants.OAuth2ServiceQueue, e =>
{
e.Consumer<CreateUserCommandConsumer>();
});
});
TaskUtil.Await(() => bus.StartAsync());
}
//CreateUserCommandConsumer.cs
public class CreateUserCommandConsumer : IConsumer<ICreateUserCommand>
{
public async Task Consume(ConsumeContext<ICreateUserCommand> context)
{
await context.RespondAsync<IUserCreatedEvent>(new
{
UserName = context.Message.UserName,
ProviderKey = "q1w2e3d3r"
});
}
}
命令和事件类如下:
//ICreateUserCommand.cs
namespace WebHost.My.ServiceBus.Messages
{
public interface ICreateUserCommand
{
string UserName { get; set; }
string Password { get; set; }
}
}
//IUserCreatedEvent.cs
namespace WebHost.My.ServiceBus.Messages.CreateUser
{
public interface IUserCreatedEvent
{
string UserName { get; set; }
string ProviderKey { get; set; }
}
}
这是我的客户端的代码(发送用户创建请求):
var bus = BusConfigurator.ConfigureBus((cfg, host) =>
{
cfg.ReceiveEndpoint(host, "profile.test.service", e =>
{
});
});
TaskUtil.Await(() => bus.StartAsync());
try
{
IRequestClient<ICreateUserCommand, IUserCreatedEvent> client = CreateRequestClient(bus);
var userName = "username";
var password = "password";
Task.Run(async () =>
{
var response = await client.Request(new CreateUserCommand()
{
UserName = userName,
Password = password
});
Console.WriteLine("User Provider key: {0}", response.ProviderKey);
Console.WriteLine("User Username: {0}", response.UserName);
}).Wait();
}
catch (Exception ex)
{
Console.WriteLine("Exception!!! OMG!!! {0}", ex);
}
finally
{
bus.Stop();
}
}
static IRequestClient<ICreateUserCommand, IUserCreatedEvent> CreateRequestClient(IBusControl busControl)
{
var serviceAddress = new Uri(RabbitMqConstants.RabbitMqUri + RabbitMqConstants.OAuth2ServiceQueue);
var client =
busControl.CreateRequestClient<ICreateUserCommand, IUserCreatedEvent>(serviceAddress, TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60));
return client;
}
重点是,这两个方面(请求方和响应方)是不同的项目,没有.ddl相同。换句话说,它们不共享IUserCreatedEvent和ICreateUserCommand接口。运行服务器代码(响应者)时,它将创建一个名为“ WebHost.My.ServiceBus.Messages:ICreateUserCommand”的交换,该交换是名称空间和接口名称的组合。由于我的客户端代码中没有这样的名称空间,因此当响应者发送提供程序密钥和用户名时,消息将转到_skipped交换,而我无法获得响应。
据我搜索和了解,Command和Event接口必须在两个项目(请求者和响应者)之间共享,但是由于我是基于基于API的项目进行编码的,所以我不希望它们共享名称空间! 如何克服MassTransit中的此类限制?
非常感谢