您的位置:首页 > 运维架构 > Apache

apache的xml-rpc(Demo实例)

2014-05-16 11:24 267 查看
RPC是Remote Procedure Call(远程过程调用),是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算”,是为了提高各个分立机器的“互操作性”而发明出来的技术。
首先来看一个小的实例,如下:
服务器端的代码如下:
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;

public class Server {
    private static final int port = 9999;

    public static void main(String[] args) throws Exception {
        WebServer webServer = new WebServer(port);   
        XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();   
        PropertyHandlerMapping phm = new PropertyHandlerMapping();
        phm.addHandler("Calculator", Calculator.class);
        xmlRpcServer.setHandlerMapping(phm);
        XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
        serverConfig.setEnabledForExtensions(true);
        serverConfig.setContentLengthOptional(false);
        webServer.start();
    }
}
class Calculator {
    public int add(int i1, int i2) {
            return i1 + i2;
    }
    public int subtract(int i1, int i2) {
            return i1 - i2;
    }
}
客户端的代码如下:
import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class Client {
    public static void main(String[] args) throws Exception {
        // create configuration
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL("http://localhost:9999/xmlrpc"));
        config.setEnabledForExtensions(true);  
        config.setConnectionTimeout(60 * 1000);
        config.setReplyTimeout(60 * 1000);
        
        XmlRpcClient client = new XmlRpcClient();
        client.setConfig(config);
        Object[] params = new Object[]{new Integer(5), new Integer(3)};
        Integer result = (Integer) client.execute("Calculator.add", params);       
        System.out.println("result : "+result);
    }
}
先启动Server,后启动Client。输出的结果为8。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: