ActiveMQ JMS usage

Context ctx;

ConnectionFactory factory;

Connection connection = null;

Session session = null;

MessageProducer producer = null;

Destination destination;

Message msg;

try {

            ctx = new InitialContext(); //Initialize, load jndi configuration file

            factory = (ConnectionFactory) ctx.lookup("connectionFactory"); //Get the connection factory

            connection = factory.createConnection(); //Create a connection

            connection.start();

            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);

            destination = session.createQueue("TEST.QUEUE");

            producer = session.createProducer(destination);

            msg = session.createTextMessage("test messages");

            System.out.println("sending message");

            producer.send(msg); //Send message

        } catch (NamingException | JMSException e) {

            e.printStackTrace ();

        } finally { //Close the connection

            try {

                if (producer != null) {

                    producer.close();

                }

            } catch (JMSException e) {

                e.printStackTrace ();

            }

            try {

                if (session != null) {

                    session.close();

                }

            } catch (JMSException e) {

                e.printStackTrace ();

            }

            try {

                if (connection != null) {

                    connection.close();

                }

            } catch (JMSException e) {

                e.printStackTrace ();

            }

        }

 

jndi.properties:

java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory

java.naming.provider.url=tcp://localhost:61616

connectionFactoryNames = connectionFactory

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326989735&siteId=291194637