同時(shí)我們需要使用SpringFramework框架,當(dāng)前版本為1.2.5。準(zhǔn)備好所有的開發(fā)包,我們要在IntelliJ IDEA創(chuàng)建一個(gè)新的項(xiàng)目,包含一個(gè)普通的模塊即可,然后設(shè)定一下classpath即可,關(guān)于項(xiàng)目的詳細(xì)信息,請(qǐng)下載附件中IntelliJ IDEA項(xiàng)目文件。
MDP的機(jī)制很簡(jiǎn)單,就是完成對(duì)指定的Message Queue或Topic的監(jiān)聽,所以我們需要在Spring的配置文件進(jìn)行設(shè)定:
1 設(shè)定ConnectionFactory,這里我們采用嵌入式方式運(yùn)行ActiveMQ:
<bean id="connectionFactory" class="org.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="vm://localhost"/> <property name="useEmbeddedBroker" value="true"/> </bean>
2 設(shè)定MDP,我們只需創(chuàng)建一個(gè)普通的JavaBean,然后實(shí)現(xiàn)MessageListener,最后在Spring配置文件中進(jìn)行設(shè)定。
<bean id="HelloMDP" class="net.jetmaven.HelloMDP"/>
3 將MDP和Queue或Topic關(guān)聯(lián)起來(lái),以下是針對(duì)ActiveMQ的設(shè)定。其中HelloMDP是對(duì)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 設(shè)定JmsTemplate,方便JMS客戶段操作。
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="defaultDestinationName" value="Hello.Queue"/> <property name="connectionFactory" ref="connectionFactory"/> </bean>
接下來(lái)我們需要?jiǎng)?chuàng)建一個(gè)Spring的JUnit測(cè)試用例,測(cè)試我們?cè)O(shè)定的功能,這里我們只需設(shè)定Spring配置文件位置,然后在測(cè)試方法中引用JmsTemplate,發(fā)送Message進(jìn)行測(cè)試。
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; } }); } }
當(dāng)你運(yùn)行這個(gè)測(cè)試時(shí),你會(huì)發(fā)現(xiàn)測(cè)試的結(jié)果。 總結(jié):通過(guò)以上的設(shè)定,我們就可以完成Spring下的Message Driven Bean的設(shè)定,同EJB的MDB相比,MDP更加簡(jiǎn)單。在上例中,我們以JVM方式啟動(dòng)ActiveMQ,這對(duì)于單個(gè)應(yīng)用(如web應(yīng)用)是非常實(shí)用的,通過(guò)這種方式可以異步發(fā)送消息,這對(duì)應(yīng)用中異步發(fā)送email,特定任務(wù)等,這種方式非常簡(jiǎn)單,原來(lái)比較復(fù)雜的問(wèn)題現(xiàn)在可以很快解決啦。
|