JesseP
JesseP

Reputation: 756

Can I make MassTransit reuse consumer instances instead of creating a new one per message?

I was (until today) under the assumption that MassTransit ServiceBusFactory's Subscribe (as used below) would take care of creating Consumers on start up, and maybe recreating them if they die off, but once things get up and running more consumers would not be created on the fly.

I was doing some performance tuning today, and discovered that my Consumer constructor is being called for what seems every single message.

Here is an example Start() method that I'm using, that registers the Consumer subscriptions (hardcoded to 1 consumer for testing).

static void Start()
        {
            var consumerLimit = ConfigurationProvider.GetSetting("ConsumerLimit", Math.Min(2, Environment.ProcessorCount));
            var controlQueueUri = ConfigurationProvider.GetServiceBusUriFromSetting("ControlQueueName");

            _bus = ServiceBusFactory.New(x =>
            {
                x.UseRabbitMq(rmq => rmq.ConfigureRabbitMqHost(ConfigurationProvider));
                x.ReceiveFrom(controlQueueUri);
                x.SetConcurrentConsumerLimit(1);                
                x.SetCreateMissingQueues(true);
                x.UseNLog();
                x.DisablePerformanceCounters();
                x.Validate();
                x.Subscribe(s => s.Consumer(() =>
                    new MyConsumer()
                    );

            });
        }

Is there a way to tell MassTransit to reuse these Consumer instances? Or do i need to assume consumers will be created for each request, and extract the heavier setup work from running for each and every consumer instance creation?

Upvotes: 2

Views: 641

Answers (1)

Travis
Travis

Reputation: 10547

Sure, this is pretty easy. So the Consumer method registers a factory, or Func that returns the consumer. So you can have a private instance of MyConsume and _myConsumer instead of new MyConsumer(). Or if you are using a container, you can set the lifecycle in the container.

Upvotes: 2

Related Questions