最近使用了一下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方法 的一個具體實現(xiàn)。服務端的代碼如下:
- 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);
- }
- }
服務端將接口以服務的形式發(fā)布后,必須提供客戶端訪問服務的地址(http://localhost:9000/Hello),客戶端可以根據(jù)提供的地址訪問服務端相關服務的wsdl文件,客戶端可以根據(jù)wsdl文件生成對應的客戶端代碼,也就是HelloWorld接口文件,然后客戶端可以像調用本地接口方法一樣,去調用遠程方法,客戶端與服務端之間的交互是通過代理完成的,所以開發(fā)在編程時不需要關系他們是如何交互的,在代理中,上面的客戶端請求hello.getWeather方法時會向服務端發(fā)送如下的消息:
<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>
服務器端接收報文后,會解析報文,按照報文的信息執(zhí)行相應的本地方法,然后將返回值又構造一個報文響應給客戶端,如下:
<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>