Tuesday, January 8, 2008

spring的Message Driven POJO (MDP)

发现SPRING的MDP很好用。不需要像MDB那么麻烦。
首先只要创建一个实现了MessageListener的POJO。
package test;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

public class MDPTest implements MessageListener {



public void onMessage(Message message) {
        if (message instanceof MapMessage) {
                MapMessage mapMsg = (MapMessage) message;

                String title;
                try {
                        title = mapMsg.getString("title");

                        System.out.println("Received: " + title);
                        System.out.println("               " + mapMsg.getString("type"));
                        System.out.println("               " + mapMsg.getString("body"));

                        System.out.println("Received: " + message);
                } catch (JMSException e) {
                        e.printStackTrace();
                }

        }
}
}
然后就是在SPRING里配置MDP所需的BEAN,一个最常用的DefaultMessageListenerContainer即可。
<!--xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Message Driven POJO (MDP) -->
<bean id="messageListener" class="test.MDPTest" />

<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://192.168.24.194:11111"/>
</bean>

<bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="IN"/>
</bean>

<!-- message listener container -->
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="destination" />
<property name="messageListener" ref="messageListener" />
</bean>
</beans>
之后只需把ACTIVEMQ配置好启动起来就OK了。当有消息进入IN这个队列时,SPRING会自动INVOKE我们的MDP。

No comments: