A kind of RPC (Remote Procedure Call
)
, besides the PRC architecture for the first time, there are Hessian, dubbo, etc.
The following only introduces the remote invocation tool that comes with java: RMI
1. External interface:
public interface IService extends Remote {
public String queryName(String no) throws RemoteException;
}
2. Service implementation:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
// service implementation
public class ServiceImpl extends UnicastRemoteObject implements IService {
/**
*/
private static final long serialVersionUID = 682805210518738166L;
/**
* @throws RemoteException
*/
protected ServiceImpl() throws RemoteException {
super();
}
/* (non-Javadoc)
*
*/
@Override
public String queryName(String no) throws RemoteException {
// concrete implementation of the method
System.out.println("hello" + no);
return String.valueOf(System.currentTimeMillis());
}
}
3.RMI client:
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
// RMI client
public class Client {
public static void main(String[] args) {
// registration manager
Registry registry = null;
try {
// Get the service registry manager
registry = LocateRegistry.getRegistry("127.0.0.1",8088);
// list all registered services
String[] list = registry.list();
for(String s : list){
System.out.println(s);
}
} catch (RemoteException e) {
}
try {
// Get service by name
IService server = (IService) registry.lookup("vince");
// call remote method
String result = server.queryName("ha ha ha ha");
// print the result of the call
System.out.println("result from remote : " + result);
} catch (AccessException e) {
} catch (RemoteException e) {
} catch (NotBoundException e) {
}
}
}
4.RMI server:
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
// RMI server
public class Server {
public static void main(String[] args) {
// registration manager
Registry registry = null;
try {
// Create a service registry manager
registry = LocateRegistry.createRegistry(8088);
} catch (RemoteException e) {
}
try {
// create a service
ServiceImpl server = new ServiceImpl();
// Name the service binding
registry.rebind("vince", server);
System.out.println("bind server");
} catch (RemoteException e) {
}
}
}
Reference link: