Need Quality Code? Get Silver Backed

MassTransit Core Patterns

15thSep

0

by Gary H

A thought is an idea in transit

Pythagoras

MassTransit is a lightweight service bus written for the .Net framework. In this post we will look at some of the core patterns used when working with MassTransit. This tutorial assumes that you are already running MassTransit with a suitable provider backing it. For help on setting this up take a look at Loosely Coupled Labs

Competing Consumers

  • Messages are added to the bus which may have 0, 1 or many subscribers
  • Each message should be processed only once (i.e. by a single subscriber)
A single provider feeds messages into MassTransit where each is distributed to only a single subscriber

Usage

This pattern is used when we need to scale up consumption of messages without the threat of processing a message multiple times. Imagine we have a billing cycle where we invoice all of our clients at the end of the month. We could add all of the generate invoice messages to the bus and then apply this pattern to spin up multiple subscribers to process each message without the fear of accidentally generating an invoice more than once.

Setup

  • Provider queue name is unique
  • All subscribers have the same queue name

Publish/Subscribe

  • Messages are added to the bus which may have 0, 1 or many subscribers
  • Each message on the bus is sent to each subscribers
  • Subscribers may be persistent or transient. Transient subscribers will only receive messages when they are attached to the bus, Persistent subscribers will have messages saved whilst they are offline and will receive them when they next reconnect
A single provider feeds messages into MassTransit where each is distributed to multiple subscribers

Usage

This pattern is used whenever we need to notify multiple subscribers about some kind of change or event. The archetypal usage may be a chat room where we update each subscriber to tell them when a new message has been typed by a participant.

Setup

  • Provider queue name is unique
  • Subscriber queue names are all unique per-instance

Common Gotchas

If a subscriber is marked as Permanent published messages will be persisted in a queue and will become available for processing by the subscriber when it next connects to the service bus.

If you extend any class which is already being consumed as its own message type, the message will be consumed twice on transmission. Once as its base class and once as the derived class. For example, given:

When inheriting from an existing message class, transmitting an instance of the new class may be consumed multiple times, once as the super class and then again as the derived class

The message will first be consumed as type Message and then again as MoreMessage.

Find this post useful? Follow us on Twitter

ServiceBus , MassTransit

Comments are Locked for this Post