The Direct Subject is the basic way to route messages in NATS. Its essence is very simple: a
subject sends messages to all consumers subscribed to it.
subject is being listened to by several consumers with the same
queue group, the message will go to a random consumer each time.
Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.
The Direct Subject is the type used in FastStream by default: you can simply declare it as follows
To begin with, we have declared several consumers for two
Note that all consumers are subscribed using the same
queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.
Now the distribution of messages between these consumers will look like this:
1 will be sent to
handler2 because they are listening to one
subject within one
2 will be sent similarly to message
3 will be sent to
handler3 because it is the only one listening to