Sending Text Message using JMS on glassfish server

2019-07-16 07:52发布

问题:

I am testing JMS with glassfish server so for that i want to send simple text message on glassfish server queue. I have tried with ActiveMQ and that is going fine but i unable to understand what can i put in configuration jndi.properties file and which jar is needed for glassfish server. Please give me some idea to implement this.

thanks in advance

回答1:

Since you're using Glassfish, the easiest way is to write simple application (EJB) that will perform the task. You have to define in GF:

  • ConnectionFactory (Resources -> JMS Resources -> Connection Factory), let's give it JNDI name jms/ConnectionFactory
  • Message queue (Resources -> JMS Resources -> Destination Resources), let's give it JNDI name jms/myQueue

Next step is to use these in some EJB that you need to write. It's not hard: firstly, you have to inject:

@Resource(mappedName="jms/ConnectionFactory")
private ConnectionFactory cf;

@Resource(mappedName="jms/myQueue")
private Queue messageQueue;

and then use it like this:

..
    javax.jms.Connection conn = null;
    javax.jms.Session s = null;
    javax.jms.MessageProducer mp = null
    try {
        conn = cf.createConnection();
        s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        mp = s.createProducer(messageQueue);
        javax.jms.TextMessage msg = s.createTextMessage();
        msg.setStringProperty("your-key", "your-value");
        msg.setText("Your text message");
        mp.send(msg);        
    }
    catch(JMSException ex) {
        // exception handling
    }
    finally {
        try {
            // close Connection, Session and MessageProducer
        } catch (JMSException ex) {
                //exception handling
        }
    }

Regarding configuration, you don't need any external JAR, everything that is needed is shipped. If you don't want to write EJB, but regular Java (standalone) application, then you'll have to include jms.jar and imq.jar.