RMI学习

1
2
3
4
5
6
7
8
package rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface MyService extends Remote {
void sayHi(String name) throws RemoteException;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class MyServiceImpl extends UnicastRemoteObject implements MyService {

private static final long serialVersionUID = -8550790423811608199L;

protected MyServiceImpl() throws RemoteException {
super();
}

public void sayHi(String name) {
System.out.println("hello " + name);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

public class RmiServer {
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}

// String server = "0.0.0.0";
String server = "10.13.139.98";
String rmiPort = "2012";
System.out.println("starting server " + server);
try {
Naming.rebind("rmi://" + server + ":" + rmiPort + "/MyService",
new MyServiceImpl());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class Client {
public static void morning() {
String server = "10.13.139.100";
String rmiPort = "2012";
try {
MyService myService = (MyService) Naming.lookup("rmi://" + server
+ ":" + rmiPort + "/MyService");
System.out.println("myService = " + myService);
myService.sayHi("Forest, Good morning!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
morning();
}
}

my.policy

codeBase "file:///C:/workspace/rmi/bin/*"{
1
2
  permission java.net.SocketPermission "0.0.0.0:2012", "connect,resolve";
};

Run commands,

1
2
3
4
5
6
7
C:\j2sdk1.4.2_10\bin\rmic.exe rmi.MyServiceImpl

rmiregistry.exe 2012

java.exe -Djava.rmi.server.hostname=10.13.139.98 -Djava.rmi.server.codebase=file:///C:/workspace/rmi/bin/ -Djava.security.policy=my.policy -cp . rmi.RmiServer

java.exe -cp . rmi.Client

注意:

  1. 如果机器上有多个IP,可以使用java.rmi.server.hostname指定其中一个,如果打印lookup后的对象,会看到MyServiceImpl_Stub[RemoteStub [ref: [endpoint:10.13.139.98:1085,objID:[f72617:1380931e011:-8000, 0]]]]
  2. java.rmi.server.codebase=file:///C:/workspace/rmi/bin/,windows下file后要有3个/,和最后要有个/
  3. my.policy中的*,代表该目录下的所有全限定类拥有权限,是classpath的路径,而不是在.class的目录

Reference

http://docs.oracle.com/javase/1.4.2/docs/guide/rmi/getstart.doc.html