Kafka Producer with MassTransit - IBusInstance has not been registered

泄露秘密 提交于 2021-01-29 06:51:24

问题


I'm trying to build a Kafka consumer using MassTransit

I have this piece of code

var services = new ServiceCollection();
services.AddMassTransit(x =>
{   
    x.AddRider(rider =>
    {
        rider.AddProducer<string, Request>("request", m => m.Message.RequestId);
        
        rider.UsingKafka((context, k) =>
        {
            k.Host("localhost:9092");
        });
    });
});

var provider = services.BuildServiceProvider();
var producer = provider.GetRequiredService<ITopicProducer<Request>>();

await producer.Produce(new Request()
{
    RequestId = "abc123",
    RequestedAt = DateTime.UtcNow
});

This is the simplest example of a producer from here

but when I try to run it, I get this exception

Unhandled exception. System.InvalidOperationException: No service for type 'MassTransit.Registration.IBusInstance' has been registered.

Looking at the example from their website, I see that it could be related to the fact that I haven't registered a RabbitMQ

x.UsingRabbitMq((context, cfg) => cfg.ConfigureEndpoints(context));

But I don't have a RabbitMQ, I only use Kafka in this scenario.

Is it necessary to register a bus with some other message broker in order to produce to Kafka?


回答1:


From the documentation:

Riders, introduced with MassTransit v7, provide a new way to deliver messages from any source to a bus. Riders are configured along with a bus, and board the bus when it is started.

To add riders, there must be a bus instance. If you don't need a bus with a durable transport such as RabbitMQ, you can use the in-memory transport.

var services = new ServiceCollection();
services.AddMassTransit(x =>
{  
    x.UsingInMemory((context,cfg) => cfg.ConfigureEndpoints(context));

    x.AddRider(rider =>
    {
        rider.AddProducer<string, Request>("request", m => m.Message.RequestId);
        
        rider.UsingKafka((context, k) =>
        {
            k.Host("localhost:9092");
        });
    });
});

The bus needs to be started and stopped, which will also start/stop any riders on the bus. You can do this via IBusControl:

var provider = services.BuildServiceProvider();
var busControl = provider.GetRequiredService<IBusControl>();

await busControl.StartAsync(cancellationToken);

Or by adding the MassTransit Hosted Service if you're using the ASP.NET Core Generic Host.

services.AddMassTransitHostedService(); // in MassTransit.AspNetCore


来源:https://stackoverflow.com/questions/63493491/kafka-producer-with-masstransit-ibusinstance-has-not-been-registered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!