大家好,有人知道如何解决 MassTransit 中的以下问题吗:消费者在其上获取请求和响应,但响应不会返回到 client.Request。方法。我在 ASP NET WEB API 中创建了项目,并通过 IRequestClient 接口(interface)实现了请求/响应通信:
public class RequestResponseCommandProvider<TRequest, TResponse>
: IRequestResponseCommandProvider<TRequest, TResponse>
where TRequest : class, ICommandQueueName
where TResponse : class
{
private readonly IBusControl _bus;
private readonly string _hostUri;
public RequestResponseCommandProvider(IBusControl bus,
string hostUri)
{
_bus = bus;
_hostUri = hostUri;
}
public TResponse RequestResponseCommand(TRequest command)
{
_bus.Start();
var serviceAddress = new Uri(_hostUri + command.QueueName);
IRequestClient<TRequest, TResponse> client =
_bus.CreateRequestClient<TRequest, TResponse>(serviceAddress, TimeSpan.FromSeconds(10));
return client.Request(command).Result; //there should back response
}
}
我已经在 Autofac 中创建了 serviceBus 的配置作为模块:
public class BusModule : Autofac.Module
{
private readonly string _hostUri;
IEnumerable<IConfigurableConsumer> _consumers;
public BusModule(string hostUri, IEnumerable<IConfigurableConsumer> consumers)
{
_hostUri = hostUri;
_consumers = consumers;
}
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies());
builder.Register(r => Bus.Factory.CreateUsingRabbitMq(sfc =>
{
var host = sfc.Host(new Uri(_hostUri), h =>
{
h.Username("guest");
h.Password("guest");
});
if (_consumers != null)
{
foreach (var consumer in _consumers)
{
consumer.Configure(sfc);
}
}
}))
.As<IBus>()
.As<IBusControl>()
.SingleInstance();
builder.RegisterType<RecieveObserver>()
.As<IReceiveObserver>();
}
}
消费者由构造函数添加。 提供者被注入(inject)到服务中:
public class TestLayer : ITestLayer
{
private readonly IRequestResponseCommandProvider<IAddTestCommand, ResponseCommand> _provider;
public TestLayer(
IRequestResponseCommandProvider<IAddTestCommand, ResponseCommand> provider)
{
_provider = provider;
}
public ServiceResult CreateTest(TestRecord record)
{
ServiceResult result;
try
{
var tmp = _provider.RequestResponseCommand(new AddTestCommand() { Record = "d3d32" });
result = new ServiceResult();
}
catch (Exception ex)
{
result = new ServiceResult();
result.AddError($"Wystąpił problem podczas zapisu do bazy danych: {ex}");
}
return result;
}
}
当我检查 RabbitMQ 中的队列时,所有消息看起来都像这样: RabbitMQ queue
我已经看过 Chris Patterson 制作的 Sample-RequestResponse,但是我在使用依赖注入(inject)时遇到了问题。 如果我做错了什么,我将不胜感激。GitHub 上还有所有存储库,您可以在其中找到包含此代码但仍然无法正常工作的简单项目:My GitHub
最佳答案
两个问题:
- 总线的惰性实例化不是一个好主意,因为它需要相当长的时间,并且在您的情况下,当
IBus
第一次被解析时,您会遇到很长的超时。 - 您没有收到任何回复,因为您需要启动总线才能接收任何信息。如果不启动总线,则只能发送。
关于asp.net - MassTransit 得到消费者的回应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558066/