RMI

一、简介
RMI (Remote Method Invocation) 是Java内置的分布式透明远程方法调用机制,客户端仅需要有远程服务的接口。EJB远程调用方式也是对RMI方式的封装,只是EJB是通过配置方式发布的远程服务,而RMI是通过编程方式发布的远程服务。

二、RMI原理

[img]http://dl2.iteye.com/upload/attachment/0109/2992/6b56b386-9f46-3879-90f9-2b8f26464cc4.png[/img]
如图所示: RMI客户端代理了服务器端接口的访问,客户端将要访问的服务器端对象名称、方法以及参数封装成对象,然后序列化为流,发送到服务器端,服务器端进行解析,然后从RMI注册对象中获取到业务对象实例,从而完成方法的调用。


三、JDK RMI示例代码
代码功能:服务器端可以接收客户端传递的字符串,并处理后返回,如果接收到quit则停止服务。
服务器端代码:

public interface RmiDemo extends Remote{//必须实现接口Remote

public String hello(String message) throws RemoteException;

}


public class RmiDemoImpl implements RmiDemo {


public String hello(String message) throws RemoteException {
if("quit".equalsIgnoreCase(message.toString().trim())){
System.out.println("Server shutdown!");
System.exit(0);
}
System.out.println("client message= "+message);
return "hello : "+message;
}

}


public class Server {

public static void main(String[] args) throws Exception{
int port=12345;//这个可以改,选一个大于1024的
String name="rmiDemo";
RmiDemo rmiDemo =new RmiDemoImpl();
UnicastRemoteObject.exportObject(rmiDemo, port);
Registry registry=LocateRegistry.createRegistry(1099);//这个不能改
registry.rebind(name, rmiDemo);
System.out.println("server is listening on " + port);

}

}


客户端代码:
public class Client {


public static void main(String[] args) throws Exception{
Registry registry=LocateRegistry.getRegistry("localhost");
String name="rmiDemo";
// RmiDemo rmiDemo =(RmiDemo) Naming.lookup(name);
//创建服务器接口的代理
RmiDemo rmiDemo =(RmiDemo) registry.lookup(name);
BufferedReader systemIn=new BufferedReader(new InputStreamReader(System.in));
while(true){
String command=systemIn.readLine();
if(command==null || "quit".equalsIgnoreCase(command.trim())){
System.out.println("Client quit!");
try{
rmiDemo.hello(command);
}
catch(Exception e){
e.printStackTrace();
}
registry.unbind(name);
System.exit(0);
}
System.out.println(rmiDemo.hello(command));
}
}

}

四、Spring RMI代码示例

Spring提供了RMI的封装,使用Spring框架则远程接口不需实现Remote接口,同普通类一样,将Remote同业务代码解耦。
服务器端代码:
public interface RmiDemo {


public String hello(String message);

}


public class RmiDemoImpl implements RmiDemo {

public String hello(String message) {
if("quit".equalsIgnoreCase(message.toString().trim())){
System.out.println("Server shutdown!");
System.exit(0);
}
System.out.println("client message= "+message);
return "hello : "+message;
}
}


public class Server {


public static void main(String[] args) throws Exception{
new ClassPathXmlApplicationContext("server.xml");
System.out.println("Server is listening...");
}

}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

<bean id="rmiDemo" class="org.frank1234.spring.rmi.RmiDemoImpl"/>

<bean id="rmiBusinessService" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service">
<ref bean="rmiDemo"/>
</property>
<property name="serviceName">
<value>rmiDemo</value>
</property>
<property name="serviceInterface">
<value>org.frank1234.spring.rmi.RmiDemo</value>
</property>
</bean>

</beans>


客户端代码:
public class Client {


public static void main(String[] args) throws Exception{
ApplicationContext context = new ClassPathXmlApplicationContext("client.xml");
RmiDemo rmiDemo =(RmiDemo) context.getBean("rmiDemo");
BufferedReader systemIn=new BufferedReader(new InputStreamReader(System.in));
while(true){
String command=systemIn.readLine();
if(command==null || "quit".equalsIgnoreCase(command.trim())){
System.out.println("Client quit!");
try{
rmiDemo.hello(command);
}
catch(Exception e){
e.printStackTrace();
}
System.exit(0);
}
System.out.println(rmiDemo.hello(command));
}
}

}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

<bean id="rmiDemo" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl">
<value>rmi://localhost/rmiDemo</value>
</property>
<property name="serviceInterface">
<value>org.frank1234.spring.rmi.RmiDemo</value>
</property>
</bean>

</beans>


五、Spring RMI相关部分关键源码

客户端:
获取服务器代理。

[img]http://dl2.iteye.com/upload/attachment/0109/2994/9b00bd20-c56a-3fd7-9b7b-fb92ef33ee26.png[/img]
服务器端:
RMI服务对象绑定和注册。

[img]http://dl2.iteye.com/upload/attachment/0109/2996/b849fb86-e272-3e65-b745-9a9f57df578f.png[/img]
将发布的原始接口封装为Remote接口。

[img]http://dl2.iteye.com/upload/attachment/0109/2998/37e387d2-a1cc-3922-a7d5-8d567cf19552.png[/img]
03-24
### Java RMI 教程及相关问题 远程方法调用 (Remote Method Invocation, RMI) 是一种用于实现客户端和服务器之间通信的技术。它允许对象在不同的虚拟机上运行并相互交互,就像它们在同一进程中一样[^1]。 #### RMI 的基本概念 RMI 提供了一种机制,使得程序可以像调用本地方法那样调用远程对象上的方法。这种技术依赖于序列化来传输数据,并通过动态代理类支持接口的透明调用[^3]。 以下是 RMI 工作的核心组件: - **Stub 和 Skeleton**: Stub 负责接收来自客户端的方法调用并将请求转发给远程对象;Skeleton 则负责将这些请求传递到实际的对象实例。 - **Registry**: 远程对象注册表是一个服务,用来存储远程对象的引用以便客户端能够查找并连接到它们。 #### 创建简单的 RMI 应用程序 要创建一个基于 RMI 的应用程序,通常需要以下几个步骤: 1. 定义远程接口:该接口必须扩展 `java.rmi.Remote` 接口,并声明所有可被远程访问的方法为抛出 `java.rmi.RemoteException` 的抽象方法。 ```java import java.rmi.*; public interface Hello extends Remote { String sayHello() throws RemoteException; } ``` 2. 实现远程接口:编写具体的实现类继承自 `UnicastRemoteObject` 并提供接口定义的功能。 ```java import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException; public class HelloImpl extends UnicastRemoteObject implements Hello { protected HelloImpl() throws RemoteException { super(); } @Override public String sayHello() throws RemoteException { return "Hello, world!"; } } ``` 3. 启动命名服务(rmiregistry),绑定远程对象至注册中心。 ```bash rmiregistry & ``` 4. 编写服务器端代码以启动服务并与注册表关联。 ```java import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Server { public static void main(String args[]) { try { Registry registry = LocateRegistry.createRegistry(1099); Hello helloObj = new HelloImpl(); registry.rebind("HelloServer", helloObj); System.out.println("Server ready"); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); } } } ``` 5. 开发客户端应用去定位远程对象并通过其 stub 来执行操作。 ```java import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { private Client() {} public static void main(String[] args) { try { Registry registry = LocateRegistry.getRegistry("localhost"); Hello stub = (Hello) registry.lookup("HelloServer"); String response = stub.sayHello(); System.out.println("response: " + response); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } } } ``` #### 常见问题排查 如果遇到与 RMI 相关的问题,可以从以下方面入手分析: - 网络配置错误可能导致无法建立连接; - 防火墙阻止了必要的端口通讯; - 类加载器未能正确处理跨 JVM 边界的类版本差异等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值