Java uses RMI
Java uses serialization to implement remote method invocation, which is very convenient when working together. This document records the use of the Java Standard library for RMI
First, the service-side structure
.├── pom.xml├── src│ ├── main│ │ └── java│ │ └── hello│ │ ├── HelloImpl.java│ │ ├── HelloServer.java│ │ └── IHello.java│ └── test│ └── java│ └── mycom│ └── AppTest.java└── target
Ihello.java
package hello;import java.rmi.Remote;import java.rmi.RemoteException;publicinterfaceextends Remote { publicsayHelloToSomeBodythrows RemoteException;
Helloimpl.java
package hello;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;publicclassextendsimplements IHello { publicHelloImplthrows RemoteException { super(); } publicsayHelloToSomeBodythrows RemoteException { System.out.println("Connected sucessfully!"); return"你好,""!"; }}
Helloserver.java
Package Hello;import java.net.MalformedURLException;import java.rmi.AlreadyBoundException;import java.rmi.Naming;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry; Public classHelloServer { Public Static void Main(String args[]) {Try{Ihello Rhello =New Helloimpl(); Locateregistry.Createregistry(8888);//If configured on a remote server, replace the address with your IPSystem.SetProperty("Java.rmi.server.hostname","127.0.0.1"); naming.Bind("Rmi://localhost:8888/rhello", Rhello); System. out.println(">>>>>info: Remote Ihello object binding succeeded! "); }Catch(RemoteException e) {System. out.println("An exception occurred creating the remote Object!" "); E.Printstacktrace(); }Catch(Alreadyboundexception e) {System. out.println("A duplicate bound object exception occurred!" "); E.Printstacktrace(); }Catch(Malformedurlexception e) {System. out.println("A malformed URL has occurred!" "); E.Printstacktrace(); } }}
Booting Helloserver.java on the server will listen to the request on port 8888.
Second, the client
The client just needs to share the interface file.
Startup code
Package Hello;import java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; Public classClient { Public Static void Main(String args[]) {Try{//Fill in the server IPIhello Rhello = (Ihello) naming.Lookup("Rmi://127.0.0.1:8888/rhello"); System. out.println(Rhello.Sayhellotosomebody("Erich")); }Catch(Notboundexception e) { }Catch(Malformedurlexception e) {e.Printstacktrace(); E.Printstacktrace(); }Catch(RemoteException e) {e.Printstacktrace(); } }}
Third, summary
As you can see, the client can perform operations as long as the interface file is available, and the specific implementation is done to the server, which can decouple calls and implementations
Java uses RMI