Sending and Receiving Messages in EJB 3 Applications
// MySenderLocal.java: the interface of the sending bean
@Local
public interface MySenderLocal {
void sendMessage(String txt) throws JMSException;
}
// MySenderLocal.java: implementation of MySenderLocal
@Stateless
public class MySender implements MySenderLocal {
@Resource(mappedName="/ConnectionFactory") // inject ConnectionFactory (more)
private ConnectionFactory factory;
@Resource(mappedName="/queue/JarfillerQueue") // inject Queue (more)
private Queue target;
// Sends the given string as text message:
public void sendMessage(String txt) throws JMSException {
Connection con = factory.createConnection();
try {
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(target);
producer.send(session.createTextMessage(txt));
}
finally {
con.close();
}
}
}
@MessageDriven( // Message-driven bean (MDB)
activationConfig = { @ActivationConfigProperty( // activation configuration (more)
propertyName = "destinationType",
propertyValue = "javax.jms.Queue"
),
@ActivationConfigProperty(
propertyName = "destination",
propertyValue = "/queue/JarfillerQueue" // destination's JNDI name
) })
public class MyMDB implements MessageListener {
public void onMessage(Message message) { // process message here
TextMessage textMsg = (TextMessage) message;
try {
System.out.println("Got message: " + textMsg.getText());
}
catch (JMSException e) {
System.out.println("Error retrieving message content");
}
}
}
How to set up JBoss 5.x
Before you can deploy the message-driven bean and the sender bean from the previous examples in a JBoss Application Server, you need to configure JBoss Messaging. In the default profile, the ConnectionFactory is already set up and available under the JNDI name "/ConnectionFactory". You can find this setting in the file "server/<profile-name>/deploy/messaging/connection-factories-service.xml".
You only need to declare your queue (or, generally speaking, your destinations). The usual place to do this is the file "server/<profile-name>/deploy/messaging/jbossmq-destination-service.xml". If the file does not exist, just create it. If it does exist, just add the following <mbean> element to jbossmq-destination-service.xml.
In order to create a single queue with the JNDI name "/queue/JarfillerQueue", the file should look like this:
<server>
<mbean code="org.jboss.mq.server.jmx.Queue"
name="jboss.mq.destination:service=Queue,name=JarfillerQueue">
<depends optional-attribute-name="DestinationManager">
jboss.mq:service=DestinationManager
</depends>
</mbean>
</server>
The prefix "/queue/" of the JNDI name comes from the file "messaging-service.xml".