muledevlepoer24
muledevlepoer24

Reputation: 207

Java ActiveMQ avoid new connection start

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class MessageSender {
    public static ConnectionFactory factory = null;
    public static Connection connection = null;
    public static Session session = null;
    public static Destination destination = null;
    public static MessageProducer producer = null;

    public static void sendMessage(String queueName,String messageContent) {
        try {
            factory = new ActiveMQConnectionFactory(
                    ActiveMQConnection.DEFAULT_BROKER_URL);            
            connection = factory.createConnection();            
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue(queueName);        
            producer = session.createProducer(destination);
            TextMessage message = session.createTextMessage();
            message.setText(messageContent);
            producer.send(message);
            System.out.println("Sent: " + message.getText() );     

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

Above is my java JMS code to push messages to the queue. Every time I want push message to queue, I used to invoke like below

MessageSender.sendMessage("orderdetailsQueue","OrderReceivedIdB6789");  

so for each message it invoke new connection.start(). How can I generalize this?

Upvotes: 1

Views: 1722

Answers (1)

hemant1900
hemant1900

Reputation: 1226

Creating connection factory and then a connection in every sendMessage is probably not a good idea.

You can move this connection factory initialization part to a singleton util class which creates the connection factory only once when that util class is instantiated. Also use the PooledConnectionFactory instead of normal connection factory which creates a pool of connections, sessions and producers. The sendMessage should get the connection by calling connectionUtil.getConnection(). The rest of the code in sendMessage looks fine except you need to release the session, producer and connection in finally by calling close() on these objects.

Pooled Connection Factory

Upvotes: 2

Related Questions