七、TheMessage-Driven Bean Class
A message drivenbean must be annotated with the MessageDriven annotation or denoted in the deploymentdescriptor as a message-driven bean. The bean class need not implement the javax.ejb.MessageDrivenBeaninterface
The class mustbe defined as public.
The class cannotbe defined as abstract or final.
It must containa public constructor with no arguments.
It must notdefine the finalize method.
It isrecommended, but not required, that a message-driven bean class implement themessage listener interface for the message type it supports. A bean thatsupports the JMS API implements the javax.jms.MessageListener interface.
Unlike sessionbeans and entities, message-driven beans do not have the remote or localinterfaces that define client access. Client components do not locatemessage-driven beans and invoke methods on them. Although message-driven beansdo not have business methods, they may contain helper methods that are invokedinternally by the onMessage method.
For theGlassFish Server, the @MessageDriven annotation typically contains a mappedNameelement that specifies the JNDI name of the destination from which the beanwill consume messages. For complex message-driven beans, there can also be anactivationconfig element containing @ActivationConfigProperty annotations usedby the bean.
A message-drivenbean can also inject a MessageDrivenContext resource. Commonly you use thisresource to call the setRollbackOnly method to handle exceptions for a beanthat uses container-managed transactions.
Therefore, thefirst few lines of the SimpleMessageBean class look like this:
@MessageDriven(mappedName="jms/Queue",activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue= "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue= "javax.jms.Queue")
})
public class SimpleMessageBean implementsMessageListener {
@Resource
private MessageDrivenContext mdc;
...
Property Name | Description |
acknowledgeMode | Acknowledgment mode; see Controlling Message Acknowledgment for information |
destinationType | Either javax.jms.Queue or javax.jms.Topic |
subscriptionDurability | For durable subscribers, set to Durable; see Creating Durable Subscriptionsfor information |
clientId | For durable subscribers, the client ID for the connection |
subscriptionName | For durable subscribers, the name of the subscription |
messageSelector | A string that filters messages; see JMS Message Selectors for information, and see An Application That Uses the JMS API with a Session Bean for an example |
addressList | Remote system or systems to communicate with; see An Application Example That Consumes Messages from a Remote Server for an example |
The onMessage Method
When the queuereceives a message, the EJB container invokes the message listener method ormethods. For a bean that uses JMS, this is the onMessage method of theMessageListener interface.
A messagelistener method must follow these rules:
The method mustbe declared as public.
The method mustnot be declared as final or static.
The onMessagemethod is called by the bean’s container when a message has arrived for thebean to service. This method contains the business logic that handles the processingof the message. It is the message-driven bean’s responsibility to parse themessage and perform the necessary business logic.
The onMessagemethod has a single argument: the incoming message.
The signature ofthe onMessage method must follow these rules:
The return typemust be void.
The method musthave a single argument of type javax.jms.Message.
In theSimpleMessageBean class, the onMessage method casts the incoming message to aTextMessage and displays the text:
public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage) {
msg = (TextMessage) inMessage;
logger.info("MESSAGE BEAN: Message received: " +
msg.getText());
} else {
logger.warning("Message of wrongtype: " +
inMessage.getClass().getName());
}
}catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
}catch (Throwable te) {
te.printStackTrace();
}
}
八、客户端
@Resource(mappedName="jms/ConnectionFactory")
private static ConnectionFactoryconnectionFactory;
@Resource(mappedName="jms/Queue")
private static Queue queue;
//Next, the client creates the connection,session, and message producer:
connection =connectionFactory.createConnection();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
messageProducer =session.createProducer(queue);
//Finally, the client sends severalmessages to the queue:
message = session.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
messageProducer.send(message);
}