primitiver JMS-Client


Quelle : http://upload.wikimedia.org/

Nur ein kleiner primitiver JMS-Client (zum Zugriff auf eine ActiveMQ-Queue) zum Senden auf eine vorgegebene Queue mit JNDI-Kontext:

import java.util.UUID;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Start {

	public static void main(String[] args) throws JMSException, NamingException {

		String uuidString = UUID.randomUUID().toString();
		String message2send = "";
		message2send += uuidString;
		message2send += "Fehler 40";
		String queueName = "inbox";
		
		Context jndiContext = new InitialContext();

		QueueConnectionFactory queueConnectionFactory = 
			(QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
		
		Queue queue = (Queue) jndiContext.lookup(queueName);

		QueueConnection queueConnection = 
			queueConnectionFactory.createQueueConnection();
		
		QueueSession queueSession = 
			queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
		
		QueueSender queueSender = queueSession.createSender(queue);
		
		TextMessage message = queueSession.createTextMessage();
		
		message.setJMSCorrelationID(uuidString);
		
		System.out.println("Sent message " + message2send);

		message.setText(message2send);
		
		queueSender.send(message);

		queueConnection.close();
	}
}

die zugehörigen jndi.properties:

# name the factory
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
 
# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616
 
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.inbox = inbox

und ein bisschen log4j-Magie:

log4j.rootLogger=INFO, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

angereichert um ein paar Maven-Dependencies:

         
		
			javax.jms
			jms
			1.1
		
		
			org.apache.activemq
			activemq-core
			5.4.1
		
		
			log4j
			log4j
			1.2.14