同時我們需要使用SpringFramework框架,當前版本為1.2.5。準備好所有的開發包,我們要在IntelliJ IDEA創建一個新的項目,包含一個普通的模塊即可,然后設定一下classpath即可,關于項目的詳細信息,請下載附件中IntelliJ IDEA項目文件。
MDP的機制很簡單,就是完成對指定的Message Queue或Topic的監聽,所以我們需要在Spring的配置文件進行設定:
1 設定ConnectionFactory,這里我們采用嵌入式方式運行ActiveMQ:
<bean id="connectionFactory" class="org.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="vm://localhost"/> <property name="useEmbeddedBroker" value="true"/> </bean>
2 設定MDP,我們只需創建一個普通的JavaBean,然后實現MessageListener,最后在Spring配置文件中進行設定。
<bean id="HelloMDP" class="net.jetmaven.HelloMDP"/>
3 將MDP和Queue或Topic關聯起來,以下是針對ActiveMQ的設定。其中HelloMDP是對MDP名稱的引用。
<bean id="activeMQContainer" class="org.activemq.jca.JCAContainer"> <property name="workManager"> <bean id="workManager" class="org.activemq.work.SpringWorkManager"/> </property> <property name="resourceAdapter"> <bean id="activeMQResourceAdapter" class="org.activemq.ra.ActiveMQResourceAdapter"> <property name="serverUrl" value="vm://localhost"/> </bean> </property> </bean> <bean id="HelloQueueConsumer" factory-method="addConnector" factory-bean="activeMQContainer"> <property name="activationSpec"> <bean class="org.activemq.ra.ActiveMQActivationSpec"> <property name="destination" value="Hello.Queue"/> <property name="destinationType" value="javax.jms.Queue"/> </bean> </property> <property name="ref" value="HelloMDP"/> </bean>
4 設定JmsTemplate,方便JMS客戶段操作。
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="defaultDestinationName" value="Hello.Queue"/> <property name="connectionFactory" ref="connectionFactory"/> </bean>
接下來我們需要創建一個Spring的JUnit測試用例,測試我們設定的功能,這里我們只需設定Spring配置文件位置,然后在測試方法中引用JmsTemplate,發送Message進行測試。
public class SpringTest extends AbstractDependencyInjectionSpringContextTests { protected String[] getConfigLocations() { return new String[]{"classpath*:applicationContext.xml"}; } public void testSendMessage() throws Exception { JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate"); jmsTemplate.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { MapMessage message=session.createMapMessage(); message.setString("name","Jacky"); return message; } }); } }
當你運行這個測試時,你會發現測試的結果。 總結:通過以上的設定,我們就可以完成Spring下的Message Driven Bean的設定,同EJB的MDB相比,MDP更加簡單。在上例中,我們以JVM方式啟動ActiveMQ,這對于單個應用(如web應用)是非常實用的,通過這種方式可以異步發送消息,這對應用中異步發送email,特定任務等,這種方式非常簡單,原來比較復雜的問題現在可以很快解決啦。
|