I am having a hard time to understand the JNDI part of the following JMS example.
public static void main(String[] args) {
try {
// Gets the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
// Sends a text message to the queue
try (JMSContext context = connectionFactory.createContext()) {
context.createProducer().send(queue, "Text message sent at " + new Date());
}
} catch (NamingException e) {
e.printStackTrace();
}
}
The book where I got this example didn't mention the setup to make this JNDI lookup possible. For example, in
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
should there be some kind of server running so that the jndiContext
can get a hold of a ConnectionFactory
object? In general, what sort of setup is required for the JNDI lookup above to work?
Thank you very much.
In general, JNDI is a service that provides a set of objects to be used by application. This service is usually provided by application server or web server or a dedicated LDAP server. If the tutorial you are trying to follow explains the JMS tutorial in the context of web application, then most likely there are some setups to be done in the application server (e.g. Glassfish, JBoss) or web server (e.g. Tomcat). The way to access JNDI also depends on the provider. Usually, this involves a configuration file (either properties file, or XML file). Another alternative to use JMS is to utilize a dedicated JMS provider such as ActiveMQ. This way, you don't need any application server. Your application can just be a standalone java application (i.e. not necessarily a web application). Accessing objects provided by ActiveMQ via JNDI is explained here: https://activemq.apache.org/jndi-support.html. General JNDI tutorial: http://docs.oracle.com/javase/tutorial/jndi/