rmi 实例
最近看到自服务系统的基本架构,里面有大量接口是调用主应用的服务,这种分布式应用应该会涉及到RMI,先看看具体实现,实现步骤大致如下:
1、生成一个远程接口
2、实现远程对象(服务器端程序)
3、生成占位程序和骨干网(服务器端程序)
4、编写服务器程序
5、编写客户程序
6、注册远程对象
7、启动远程对象
package RMI;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* RMI远程接口
* @author yaohonv
*/
public interface ServiceMethodI extends Remote{
String getMessage() throws RemoteException;
}
package RMI;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* RMI接口实现
* @author yaohonv
*/
public class ServiceMethod extends UnicastRemoteObject implements ServiceMethodI {
public String getMessage() throws RemoteException {
return "hello,this is service";
}
public ServiceMethod() throws RemoteException {
super();
}
}
启动服务main方法:
package RMI;
import java.rmi.Naming;
/**
* 服务器,用于上面写好的类
* @author yaohonv
*
*/
public class RMIService {
public static void main(String[] args) {
//System.setSecurityManager(new RMISecurityManager());
try {
ServiceMethod sm = new ServiceMethod();
//rmi://127.0.0.1:1099/yaohonv_ServiceMethod
//端口1099是默认的RMI端口,如果你启动 rmiregistry 的时候(见第6点)没有指定特殊的端口号,默认就是1099
Naming.rebind("yaohonv_ServiceMethod", sm);
System.out.println("this is remote class ,Ready to give service");
} catch (Exception e) {
e.printStackTrace();
}
}
}
编译服务器端类。
:F:yao_zone estJspsrc>javac RMI*.java
生成根和干(占位程序和骨干程序)。(这个步骤不进行,似乎也没有报错,或许是只需要调用一次)
:F:yao_zone estJspsrc>rmic -classpath . -d . RMI.ServiceMethod
开启RMI的注册服务,开启以后我们的server程序才能调用rebing方法发布我们的类。
:F:yao_zone estJspsrc>start rmiregistry
启动远程服务:
:F:yao_zone estJspsrc>java -Djava.rmi.server.codebase=file:/F:yao_zone estJspsrcRMI/ RMI.RMIService
客户端调用程序:
package RMIclient;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import RMI.ServiceMethodI;
/**
* 测试RMI
* @author yaohonv
*/
public class TestRMI {
public static void main(String[] args) {
System.setSecurityManager(new RMISecurityManager());
try {
ServiceMethodI t = (ServiceMethodI) Naming.lookup("yaohonv_ServiceMethod");
System.out.println("client =" + t.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
启用客户端
java RMIclient.TestRMI,报错:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)
崩溃,权限问题。
这是因为RMI的服务需要授权,外部程序才能访问,所以我们要改动 jre的安全配置文件,来开放权限, 具体如下:
打开你的jdk目录下的这个文件 D:Program FilesJavajdk1.5.0_15jrelibsecurityjava.policy
在文件最后加入下面代码:
grant {
permission java.net.SocketPermission "*:1024-65535",
"connect,accept";
permission java.net.SocketPermission "*:80","connect";
};
重新运行客户端
F:yao_zone estJspsrc>java RMIclient.TestRMI
client =hello,this is service
OK,成功调用
此代码,开放了端口的connect访问权限
注意:你应该修改服务器那台机子的安全配置文件,也就是你运行 rmiregistry 和 RMI_Server的机子