2.2. Co-locating the Broker

Overview

An obvious way to improve network performance is to eliminate one of the hops in the messaging application. With a standalone broker, at least two hops are required to route a message from producer to consumer: the producer-to-broker hop and the broker-to-consumer hop. On the other hand, by embedding the broker (either in the producer or in the consumer), it is possible to eliminate one of the hops, thereby halving the load on the network.
Figure 2.1, “Broker Co-located with Producer” shows an example of a data feed that acts as a message producer, sending a high volume of messages through the broker. In this case, it makes perfect sense for the broker to be co-located with the data feed, so that messages can be sent directly to the consumers, without the need for an intermediate hop. The simplest way to create an embedded broker is to exploit Red Hat JBoss A-MQ's vm:// transport.

Figure 2.1. Broker Co-located with Producer

Broker Co-located with Producer

The vm:// transport

You can connect to a vm:// endpoint from a producer or a consumer in just the same way as you connect to a tcp:// endpoint (or any other protocol supported by Red Hat JBoss A-MQ). But the effect of connecting to a vm:// endpoint is quite different from conecting to a tcp:// endpoint: whereas a tcp:// endpoint initiates a connection to a remote broker instance, the vm:// endpoint actually creates a local, embedded broker instance. The embedded broker runs inside the same JVM as the client and messages are sent to the broker through an internal channel, bypassing the network.
For example, an Apache Camel client can create a simple, embedded broker instance by connecting to a URL of the following form:
vm://brokerName
Where brokerName uniquely identifies the embedded broker instance. This URL creates a simple broker instance with a default configuration. If you want to define the broker configuration precisely, however, the most convenient approach is to specify a broker configuration file, by setting the brokerConfig option. For example, to create a myBroker instance that takes its configuration from the activemq.xml configuration file, define the following VM endpoint:
vm://myBroker?brokerConfig=xbean:activemq.xml
For more details, see the Connection Reference.

A simple optimization

By default, the embedded broker operates in asynchronous mode, so that calls to a send method return immediately (in other words, messages are dispatched to consumers in a separate thread). If you turn off asynchronous mode, however, you can reduce the amount of context switching. For example, you can disable asynchronous mode on a VM endpoint as follows:
vm://brokerName?async=false
Note
If both the broker option, optimizedDispatch, and the consumer option, dispatchAsync, are also configured to disable asynchronous behavior, the calling thread can actually dispatch directly to consumers.