MDB就是异步消息的消费者。当消息到达之后,由容器负责调用MDB。客户端发送消息到destination,MDB作为一个MessageListener接受消息。用程序员去关心MessageBean的管理。
MDB只是作为服务器端接收消息,而且ConnectionFacotory和JNDI都要自己去服务器上配置。
1、Weblogic配置JMS服务
具体JMS在weblogic服务器配置请看:http://qidaoxp.iteye.com/admin/blogs/480058
2、Example Bean
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
* Demonstrates usage of a Message-Driven EJB.
*
* @author Copyright (c) 1999-2008 by BEA Systems, Inc. All Rights Reserved.
*/
public class MessageTraderBean implements MessageDrivenBean, MessageListener {
private static final boolean VERBOSE = true;
private MessageDrivenContext m_context;
private int m_tradeLimit;
/**
* Sets the session context.
*
* @param ctx MessageDrivenContext Context for session
*/
public void setMessageDrivenContext(MessageDrivenContext ctx) {
m_context = ctx;
}
/**
* Retrieve the int value of the TextMessage and
* increment the RMI counter by that much.
*/
public void onMessage(Message msg) {
TextMessage tm = (TextMessage) msg;
try {
String text = tm.getText();
log("Received new quote : "+text);
}
catch(JMSException ex) {
System.err.println("An exception occurred: "+ex.getMessage());
}
}
/**
* This method is required by the EJB Specification,
* but is not used by this example.
*/
public void ejbCreate() { }
/**
* This method is required by the EJB Specification,
* but is not used by this example.
*/
public void ejbRemove() { }
static void p(String s) {
System.out.println("*** <MessageTraderBean> "+s);
}
private void log(String s) {
if (VERBOSE) System.out.println(s);
}
}
3、ejb-jar.xml
<ejb-jar>
<enterprise-beans>
<message-driven>
<display-name>MessageTraderBean</display-name>
<ejb-name>MessageTraderBean</ejb-name>
<ejb-class>ejb.mdb.MessageTraderBean</ejb-class>
<transaction-type>Container</transaction-type>
<message-destination-type>javax.jms.Topic</message-destination-type>
</message-driven>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>MessageTraderBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
4、weblogic-ejb-jar.xml
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>MessageTraderBean</ejb-name>
<message-driven-descriptor>
<destination-jndi-name>testtopic</destination-jndi-name>
</message-driven-descriptor>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
注意destination-jndi-name为自己在服务器上配置的jndi要一致。