Purpose
This case will show how to create an MDB(message dirven bean) in EJB3 specification, and call it by two ways, one is use spring framework, another is call it directly. This case is aim to have a small view of JMS of EJB.
ENV and Container Setting
Here we use Jboss5.0GA, attention if you use Jboss4.X, it maybe have some different.
Setting of JMS in Jboss 5.0.GA
1.copy your database dirver jar to jboss lib if you will use database.
2.copy $JBOSS_HOME$/docs\examples\jca\mysql-ds.xml to server\default\deploy (if use mysql)
3.modify this mysql-ds.xml as:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: mysql-ds.xml 41017 2006-02-07 14:26:14Z acoliver $ -->
<!-- Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->
<datasources>
<local-tx-datasource>
<jndi-name>MySqlDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/test</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password>root</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<!-- should only be used on drivers after 3.22.1 with "ping" support
<valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
-->
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->
<!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
4.copy $JBOSS_HOME$/docs/examples/jms/mysql-persistence-service.xml to server\default\deploy\messaging, and delete hsqldb-persistence-service.xml file.
Then edit it as:
<!-- Messaging Post Office MBean configuration
========================================= -->
<mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
name="jboss.messaging:service=PostOffice"
xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
<depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
<depends>jboss.jca:service=DataSourceBinding,name=MySqlDS</depends>
<depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
<!-- The name of the post office -->
<attribute name="PostOfficeName">JMS post office</attribute>
<!-- The datasource used by the post office to access it's binding information -->
<attribute name="DataSource">java:/MySqlDS</attribute>
<!-- If true will attempt to create tables and indexes on every start-up -->
<!--<attribute name="CreateTablesOnStartup">true</attribute>-->
<attribute name="SqlProperties"><![CDATA[
CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID INTEGER, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023), CHANNEL_ID BIGINT, CLUSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME)) ENGINE = INNODB
INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
]]></attribute>
<!-- This post office is non clustered. If you want a clustered post office then set to true -->
<attribute name="Clustered">false</attribute>
<!-- All the remaining properties only have to be specified if the post office is clustered.
You can safely comment them out if your post office is non clustered -->
<!-- The JGroups group name that the post office will use -->
<!-- <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute> -->
<!-- Max time to wait for state to arrive when the post office joins the cluster -->
<!--<attribute name="StateTimeout">30000</attribute>-->
<!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
<!--<attribute name="CastTimeout">30000</attribute>-->
<!-- Set this to true if you want failover of connections to occur when a node is shut down -->
<!--<attribute name="FailoverOnNodeLeave">false</attribute>-->
<!--<depends optional-attribute-name="ChannelFactoryName">jboss.jgroups:service=ChannelFactory</depends>-->
<!--<attribute name="ControlChannelName">jbm-control</attribute>-->
<!--<attribute name="DataChannelName">jbm-data</attribute>-->
<!--<attribute name="ChannelPartitionName">${jboss.partition.name:DefaultPartition}-JMS</attribute>-->
</mbean>
5.If you want to use spring jms, you should edit file destinations-service.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Messaging Destinations deployment descriptor. $Id:
destinations-service.xml 81998 2008-12-03 06:46:29Z
scott.stark@jboss.org $
-->
<server>
<!--
The Default Dead Letter Queue. This destination is a dependency of an
EJB MDB container. SpringJMSServer
-->
<mbean code="org.jboss.jms.server.destination.QueueService" name="jboss.messaging.destination:service=Queue,name=DLQ"
xmbean-dd="xmdesc/Queue-xmbean.xml">
<depends optional-attribute-name="ServerPeer">
jboss.messaging:service=ServerPeer</depends>
<depends>jboss.messaging:service=PostOffice
</depends>
</mbean>
<!--
The Default Expiry Queue.
-->
<mbean code="org.jboss.jms.server.destination.QueueService"
name="jboss.messaging.destination:service=Queue,name=ExpiryQueue"
xmbean-dd="xmdesc/Queue-xmbean.xml">
<depends optional-attribute-name="ServerPeer">
jboss.messaging:service=ServerPeer</depends>
<depends>jboss.messaging:service=PostOffice
</depends>
</mbean>
<!-- add by daniel zhou 2009-07-21 -->
<mbean code="org.jboss.jms.server.destination.QueueService"
name="jboss.messaging.destination:service=Queue,name=SpringJMSServer"
xmbean-dd="xmdesc/Queue-xmbean.xml">
<depends optional-attribute-name="ServerPeer">
jboss.messaging:service=ServerPeer</depends>
<depends>jboss.messaging:service=PostOffice
</depends>
</mbean>
</server>
Mian Code
MDB Part in EJB3
In ejb3 is more easier than ejb2.1 in MDB create and description, as you know the main reason is annotation from JDK5.
package jms;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
* Message-Driven Bean implementation class for: MessageReceive
*
*/
@MessageDriven(activationConfig = {
//Message type
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
//Destination of Message
@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/SpringJMSServer")
})
public class MessageReceive implements MessageListener {
/**
* Default constructor.
*/
public MessageReceive() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
//tm
TextMessage tm = (TextMessage) message;
//out
try {
System.out.println("Get text:"+tm.getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Spring part
xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.provider.url">localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jboss.naming</prop>
</props>
</property>
</bean>
<bean id="jmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>ConnectionFactory</value>
</property>
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>queue/SpringJMSServer</value>
</property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate102">
<property name="connectionFactory">
<ref bean="jmsQueueConnectionFactory" />
</property>
<property name="defaultDestination">
<ref bean="destination" />
</property>
<property name="receiveTimeout">
<value>30000</value>
</property>
</bean>
<bean id="jmsSender" class="jms.send.JMSSender">
<property name="jmsTemplate">
<ref bean="jmsTemplate" />
</property>
</bean>
</beans>
Bean
package jms.send;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
public class JMSSender {
private JmsTemplate jmsTemplate;
/**
*
*/
public JMSSender() {
}
public void sendMessage(final String message) {
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
TextMessage text = session.createTextMessage();
text.setText(message);
return text;
}
});
}
/**
* @return the jmsTemplate
*/
public JmsTemplate getJmsTemplate() {
return jmsTemplate;
}
/**
* @param jmsTemplate
* the jmsTemplate to set
*/
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
}
Test class
/**
*
*/
package jms.test;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jms.send.JMSSender;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author daniel 2009-07-22
*
*/
public class JMSTest {
/**
* @param args
*/
public static void main(String[] args) {
//call by spring
JMSTest.sendMessageBySpringBean();
//call directly
JMSTest.sendMessageDriectly();
}
/**
* Send Message directly
*/
public static void sendMessageDriectly(){
QueueConnection conn=null;
QueueSender sender=null;
QueueSession sess=null;
Queue queue=null;
Properties props=new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
try {
InitialContext ctx=new InitialContext(props);
//get connection factory
QueueConnectionFactory factory=(QueueConnectionFactory) ctx.lookup("ConnectionFactory");
//use connection factory create JMS connection
conn=factory.createQueueConnection();
//use JMS create Session
sess=conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
//get the jndi
queue=(Queue) ctx.lookup("queue/SpringJMSServer");
//create message publisher
sender=sess.createSender(queue);
//create message
TextMessage msg=sess.createTextMessage("hello kids,this is daniel's message bean。");
//publish message
sender.send(msg);
sess.close();
//end massage
System.out.println("Message have been send, you can see them in jboss console");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Send message by spring
*/
public static void sendMessageBySpringBean() {
System.out.println("Class loader initialize start...");
ApplicationContext app = new ClassPathXmlApplicationContext(
"applicationContext.xml");
JMSSender jmsSender = (JMSSender) app.getBean("jmsSender");
System.out.println("Class loader initialize end...");
System.out.println("Send message start...");
for (int index = 0; index < 10; index++) {
jmsSender.sendMessage("This is " + index + "time to say:hello jms!");
}
System.out.println("Send message end...");
}
}
Attention in Spring
In spring, you should import lib jars about JMS, such as commons-logging.jar
,jmscommon.jar and attention because we use jboss here, so you should import which client jars, this is important point! Of course, beside them, spring.jar must be included, don't forget it!
If not, you can run spring and use MDB smoothly, if you still could not deal with it, contact me by msn:danni-505@hotmail.com
Source DownLoad