Use Javax XML RPC A
Use Javax XML RPC A
Overview:
Remote Procedure Call (RPC) is a commonly used communication mechanism to call remote services or functions in a distributed system.Javax XML RPC API is a way to implement RPC provided in the Java standard library, which can easily realize the remote calls of the Java library.
step:
1. Create a Java class as an implementation class for the RPC service. This class contains methods to call remotely.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
2. Create a Java interface to define the method of remote calling.
public interface CalculatorService {
public int add(int a, int b);
}
3. Create a server class for RPC services.
public class CalculatorServer {
public static void main(String[] args) {
try {
Calculator calculator = new Calculator();
CalculatorService calculatorService = (CalculatorService) calculator;
// Create an RPC server
WebServer server = new WebServer(8080);
// Register RPC service
XmlRpcServer xmlRpcServer = server.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler("Calculator", calculatorService.getClass());
xmlRpcServer.setHandlerMapping(phm);
// Start the RPC server
server.start();
System.out.println ("The RPC server has been started, is listening to the port 8080 ...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Create a client class to call remote methods.
public class CalculatorClient {
public static void main(String[] args) {
try {
// Create an RPC client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:8080/xmlrpc"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
// Call the remote method
Object[] params = {2, 3};
int result = (int) client.execute("Calculator.add", params);
System.out.println ("Remote call result:" + Result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. Run the Calculatorserver class to start the RPC server.
6. Run the remote method of calling the CALCULERCLIENT class and obtain the results.
in conclusion:
Through the Javax XML RPC API, we can easily implement the remote process calls of the Java class library.By creating server and client, we can call the remote Java method in a distributed system.This method is simple and easy to use, suitable for various distributed application scenarios.