|
最近使用了一下cxf,簡單的查看了部分源代碼,給我的感覺它就是一個可以大大簡化我們客戶端編寫遠(yuǎn)程方法調(diào)用的一個工具框架,只需要簡單的幾行代碼就可以解決這種復(fù)雜的問題,下面就舉個例子: import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.transport.jms.spec.JMSSpecConstants; import com.erayt.solar2.adapter.config.Weather; import com.erayt.solar2.adapter.fixed.HelloWorld; public class CXFClientTest { public static void main(String[] args) { ClientProxyFactoryBean factory = new ClientProxyFactoryBean(); factory.setTransportId(JMSSpecConstants.SOAP_JMS_SPECIFICATION_TRANSPORTID); factory.setAddress("http://localhost:9000/Hello"); HelloWorld hello = factory.create(HelloWorld.class); Weather weather1 = hello.getWeather(new Date()); System.out.println("forecast:" + weather1.getForecast());
上面一段是客戶端調(diào)用遠(yuǎn)程服務(wù)器中HelloWorld接口的getWeather方法 的一個具體實現(xiàn)。服務(wù)端的代碼如下: package com.erayt.solar2.adapter.driver; import org.apache.cxf.frontend.ServerFactoryBean; import com.erayt.solar2.adapter.config.HelloWorldImpl; import com.erayt.solar2.adapter.fixed.HelloWorld; protected CXFServer() throws Exception { HelloWorld helloworldImpl = new HelloWorldImpl(); ServerFactoryBean svrFactory = new ServerFactoryBean(); svrFactory.setServiceClass(HelloWorld.class); svrFactory.setAddress("http://localhost:9000/Hello"); svrFactory.setServiceBean(helloworldImpl); public static void main(String args[]) throws Exception { System.out.println("Server ready..."); Thread.sleep(50 * 60 * 1000); System.out.println("Server exiting");
服務(wù)端將接口以服務(wù)的形式發(fā)布后,必須提供客戶端訪問服務(wù)的地址(http://localhost:9000/Hello),客戶端可以根據(jù)提供的地址訪問服務(wù)端相關(guān)服務(wù)的wsdl文件,客戶端可以根據(jù)wsdl文件生成對應(yīng)的客戶端代碼,也就是HelloWorld接口文件,然后客戶端可以像調(diào)用本地接口方法一樣,去調(diào)用遠(yuǎn)程方法,客戶端與服務(wù)端之間的交互是通過代理完成的,所以開發(fā)在編程時不需要關(guān)系他們是如何交互的,在代理中,上面的客戶端請求hello.getWeather方法時會向服務(wù)端發(fā)送如下的消息: <soap:Envelope xmlns:soap="http://schemas./soap/envelope/">
<soap:Body>
<ns1:getWeather xmlns:ns1="http://fixed.adapter.solar2./">
<arg0>2013-06-22T18:56:43.808+08:00</arg0>
</ns1:getWeather>
</soap:Body>
</soap:Envelope> 服務(wù)器端接收報文后,會解析報文,按照報文的信息執(zhí)行相應(yīng)的本地方法,然后將返回值又構(gòu)造一個報文響應(yīng)給客戶端,如下: <soap:Envelope xmlns:soap="http://schemas./soap/envelope/">
<soap:Body>
<ns1:getWeatherResponse xmlns:ns1="http://fixed.adapter.solar2./">
<return>
<forecast>Cloudy with
showers
</forecast>
<howMuchRain>4.5</howMuchRain>
<rain>true</rain>
<temperature>39.3</temperature>
</return>
</ns1:getWeatherResponse>
</soap:Body>
</soap:Envelope>
|