Search code examples
javajmsmessagebrokerbroker

How to write a JMS Broker?


How does the Java Message Service work concerning brokers? I see tutorials and examples for creating producer & consumer clients, but I do not understand how to involve a broker with JMS. I see that there is e.g. ActiveMQ where one can easily have a class to implement a broker, but then it looks like I also have to use ActiveMQ methods in my clients to build up a connection to the broker instead of using pure JMS methods?


Solution

  • The JMS API is essentially a client API. It defines the API a client would use to interact with a broker. How the broker is implemented is completely arbitrary granted that the behavior of the implementation adheres to the JMS specification. This gives those who are implementing a JMS broker ample freedom to implement it in a way that suits their own requirements and constraints. This also means that creating and configuring an instance of a broker (whatever broker that might be) is not defined by the JMS API.

    Furthermore, the JMS specification establishes the convention that clients are able to find their "admin objects" (i.e. connection factories and destinations) in JNDI. Section 5.1 of the JMS 2 specification states:

    Although the interfaces for administered objects do not explicitly depend on JNDI, JMS establishes the convention that JMS clients find them by looking them up in a namespace using JNDI.

    Because of this convention most JMS providers also provide a JNDI implementation to use along with the JMS implementation. ActiveMQ provides this via the org.apache.activemq.jndi.ActiveMQInitialContextFactory class. Usage and configuration of this JNDI implementation is discussed further in the ActiveMQ documentation.

    Since using JNDI is just a convention most JMS providers have alternate ways of accessing admin objects. For example, ActiveMQ allows you to programmatically instantiate a connection factory or destination using ActiveMQ-specific classes.

    To connect a JMS client to its corresponding broker you first need to decide whether you want to use JNDI or a provider-specific mechanism. Generally speaking JNDI is the preferred method as it is pluggable (using properties defined in the jndi.properties file on the application's classpath) which makes it easier to switch between JMS brokers if the need arises. Once that decision is made then you acquire an instance of javax.jms.ConnectionFactory and use that to create your javax.jms.Connection, etc. There are lots of tutorials and documentation on how to write JMS clients after this point.

    Ultimately there is no strict need to use anything other than the JMS and JNDI APIs in your client applications when connecting to ActiveMQ.