最近使用了一下cxf,簡單的檢視了部分源代碼,給我的感覺它就是一個可以大大簡化我們用戶端編寫遠端方法調用的一個工具架構,隻需要簡單的幾行代碼就可以解決這種複雜的問題,下面就舉個例子:
package com.yonge.cxf;
import java.util.Date;
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());
}
}
上面一段是用戶端調用遠端伺服器中HelloWorld接口的getWeather方法 的一個具體實作。服務端的代碼如下:
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;
public class CXFServer {
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);
svrFactory.create();
}
public static void main(String args[]) throws Exception {
new CXFServer();
System.out.println("Server ready...");
Thread.sleep(50 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
服務端将接口以服務的形式釋出後,必須提供用戶端通路服務的位址(http://localhost:9000/Hello),用戶端可以根據提供的位址通路服務端相關服務的wsdl檔案,用戶端可以根據wsdl檔案生成對應的用戶端代碼,也就是HelloWorld接口檔案,然後用戶端可以像調用本地接口方法一樣,去調用遠端方法,用戶端與服務端之間的互動是通過代理完成的,是以開發在程式設計時不需要關系他們是如何互動的,在代理中,上面的用戶端請求hello.getWeather方法時會向服務端發送如下的消息:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:getWeather xmlns:ns1="http://fixed.adapter.solar2.erayt.com/">
<arg0>2013-06-22T18:56:43.808+08:00</arg0>
</ns1:getWeather>
</soap:Body>
</soap:Envelope>
伺服器端接收封包後,會解析封包,按照封包的資訊執行相應的本地方法,然後将傳回值又構造一個封包響應給用戶端,如下:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:getWeatherResponse xmlns:ns1="http://fixed.adapter.solar2.erayt.com/">
<return>
<forecast>Cloudy with
showers
</forecast>
<howMuchRain>4.5</howMuchRain>
<rain>true</rain>
<temperature>39.3</temperature>
</return>
</ns1:getWeatherResponse>
</soap:Body>
</soap:Envelope>
代理接收消息後,會将他解析、包裝成對象傳回給用戶端,最後開發就看到了伺服器傳回的資料了。在這裡隻介紹一下我了解的工作原理,詳情可以去看官網的介紹http://cxf.apache.org/。