In many messaging topologies there are JMS Brokers (server side) and a JMS client side. Often it makes sense to deploy a broker within your JVM. This allows you to optimise away a network hop; making the networking of JMS as efficient as pure RMI, but with all the usual JMS features of location independence, reliability, load balancing etc.
There are various ways to embed a broker in ActiveMQ depending on if you are using Java, Spring, XBean or using the ActiveMQConnectionFactory .
The following Java code will create an embedded broker
If you want to lazily bind the transport connector as part of start(), useful when start() will block pending a store lock (as in a slave start), you can use the following code
If you have more than one embedded broker, ensure that you give them a unique name and - e.g.
Then if you want to connect to the broker named 'fred' from within the same JVM, you can by using the uri vm://fred
It is possible to fully configure a broker through application code e.g.
For more details on the available properties you can specify, see the BrokerService javadoc
There is a helper class called BrokerFactory which can be used to create a broker via URI for configuration.
The available values of the URI are
There is a factory bean that can refer to an external ActiveMQ XML configuration file
In this case the usual Spring 'classpath:org/apache/activemq/xbean/activemq.xml' resource mechanism is being used so that the activemq.xml file would be found on the classpath by looking inside all the directories on the classpath then looking for 'org/apache/activemq/xbean/activemq.xml'. You can of course change this to any value you like. e.g. use classpath:activemq.xml if you just want to drop it in a directory that is in the classpath; like WEB-INF/classes in a web application.
If you are using Spring 2.0 and ActiveMQ 4.1 or later (and xbean-spring 2.5 or later) you can embed the ActiveMQ broker XML inside any regular Spring.xml file without requiring the above factory bean. e.g. here is an example of a regular Spring XML file in Spring 2.0 which also configures a broker.
An embedded broker can also be created using an ActiveMQConnectionFactory and using a vm connector as a uri. e.g.
Use the query parameters "broker.<property>" to configure the broker, where <property> matches the bean properties on the BrokerService.
The broker will be created upon creation of the first connection.
You can turn off auto creation by setting the create property on the VM Transport to false: