現(xiàn)在試試通過JMS,在應(yīng)用程序之間發(fā)送消息。先看看sPRing提供的RPC方案(其實(shí)還有其他方案,只是沒見過誰用)。需要使用到這兩個(gè)類:·org.springframework.jms.remoting.JmsInvokerServiceExporter將bean導(dǎo)出為基于消息的服務(wù)·org.springframework.jms.remoting.JmsInvokerProxyFactoryBean讓客戶端調(diào)用服務(wù)
比較一下JmsInvokerServiceExporter和RmiServiceExporter:

package pac.testcase.jms;public interface JmsRmiService { String doServe(String requestedNum);}package pac.testcase.jms;import org.springframework.stereotype.Service;@Servicepublic class JmsRmiServiceImpl implements JmsRmiService { public String doServe(String content) { System.out.println(content.concat(" has been requested!!")); return "your message::".concat(content).concat(":::length:")+content.length(); }}將這個(gè)pojo聲明為服務(wù),在spring配置文件中配置:
<bean id="serverService" class="org.springframework.jms.remoting.JmsInvokerServiceExporter" p:serviceInterface="pac.testcase.jms.JmsRmiService" p:service-ref="JmsRmiServiceImpl"></bean>
需將他設(shè)置為jms監(jiān)聽器,配置方法和一般的jmsMessageListener的配置相同:
<amq:connectionFactory id="jmsFactory" /><jms:listener-container destination-type="queue" connection-factory="jmsFactory" concurrency="3" container-type="simple"> <jms:listener destination="sparta" ref="serverService" /></jms:listener-container>
container-type有simple和default,根據(jù)不同的type也可以使用task-Executor,這里先簡(jiǎn)單記錄一下。
先啟動(dòng)jms broker再啟動(dòng):
new ClassPathxmlapplicationContext("classpath:applicationContext-*.xml").getBean(JmsRmiService.class);
client這邊我需要一個(gè)調(diào)用代理幫我去調(diào)用接口,也就是JmsInvokerProxyFactoryBean;配置如下:
<amq:connectionFactory id="connectionFactory" /><bean id="clientService" class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean" p:serviceInterface="pac.test.jms.SenderRmiService" p:connectionFactory-ref="connectionFactory" p:queueName="sparta"/>
配置中的serviceInterface是client端中根據(jù)要調(diào)用的方法創(chuàng)建的一個(gè)接口。
main方法試著調(diào)用看看:
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); SenderRmiService service = (SenderRmiService)context.getBean("clientService"); System.out.println(service.doServe("這才是斯巴達(dá)!!"));}server端輸出:
client端輸出:
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注