rmi
common包
IHelloService
public interface IHelloService extends Remote {
String sayHello(User user) throws RemoteException;
}
User
public class User implements Serializable,Cloneable{
public User(String name , int age){
this.name=name;
this.age=age;
}
String name ;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Server
HelloServiceImpl
public class HelloServiceImpl extends UnicastRemoteObject implements IHelloService {
public HelloServiceImpl() throws RemoteException {
}
@Override
public String sayHello(User user) throws RemoteException {
// MyLog.info("this is server, say Hello to :"+ user.getName());
return "success";
}
}
RMIServer
public class RMIServer {
public static void main(String []args) throws RemoteException {
IHelloService helloService=new HelloServiceImpl();
// IHelloService helloService1=(IHelloService) UnicastRemoteObject.exportObject(helloService,0);
// Bind the remote object's stub in the registry
// StaticRmiSocketFactory regFac = new StaticRmiSocketFactory("172.16.51.214", 2002);
Registry registry = LocateRegistry.createRegistry(2002 );
registry.rebind("helloService", helloService);
MyLog.info("server is ready");
}
}
Client
RMIClient
public class RMIClient {
public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
User user = new User("JackMa", 55);
int max = Runtime.getRuntime().availableProcessors() *2 ;
for (int k = 0; k < max; k++) {
new Thread(() -> {
Registry registry = null;
try {
registry = LocateRegistry.getRegistry("172.16.51.214", 2002);
IHelloService helloService = (IHelloService) registry.lookup("helloService");
int count = 1000000;
MyLog.info("start : " + count);
for (int i = 0; i < count; i++) {
try {
helloService.sayHello(user);
} catch (RemoteException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
MyLog.info("end");
}).start();
}
}
}

浙公网安备 33010602011771号