Spring整合RMI
2019-01-24 本文已影响0人
Tim在路上
经常使用Java的一定知道RMI,当需要远程调用服务的是否,Java内嵌的RMI是非常有用的。但是创建调用RMI的服务是很麻烦的,Spring简化了RMI的使用,不用抛出RemoteException异常的特定RMI类,只需实现服务功能的pojo即可。
服务端使用了org.springframework.remoting.rmi.RmiServiceExporter
RmiServiceExporter把任何Spring管理的Bean输出成一个RMI服务。通过把Bean包装在一个适配器类中工作。适配器类被绑定到RMI注册表中,并且将请求代理给服务类。
客户端使用了org.springframework.remoting.rmi.RmiProxyFactoryBean
客户端的核心是RmiProxyFactoryBean,包含serviceURL属性和serviceInterface属性。
通过JRMP访问服务。JRMP JRMP:java remote method protocol,Java特有的,基于流的协议。
Spring-RMI
- 实现服务端
- 创建接口
public interface IRmiServer {
public boolean test();
}
- 实现该方法
public class RmiServerImpl implements IRmiServer {
@Override
public boolean test() {
System.out.println("调--服务端");
return true;
}
}
- 在Spring的配置文件中配置RMI
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.5//EN" "file:/usr/local/tomcat_report/lib/spring-beans-2.0.dtd">
<beans>
<!-- rmi -->
<bean id="rmiService" class="com.cayden.rmi.impl.RmiServerImpl">
</bean>
<bean id="remoteRmiService" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName">
<value>remoteService</value>
</property>
<property name="service" ref="rmiService" />
<property name="serviceInterface">
<value>com.cayden.rmi.IRmiServer</value>
</property>
<property name="registryPort">
<value>9400</value>
</property>
<property name="servicePort">
<value>9401</value>
</property>
</bean>
</beans>
启动服务端
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("rmi服务端启动");
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
- 创建客户端
- 使用服务端的接口文件
public interface IRmiServer {
public boolean test();
}
- 在Spring的配置文件中添加rmi远程调用
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.5//EN" "file:/usr/local/tomcat_report/lib/spring-beans-2.0.dtd">
<beans>
<!-- rmi远程调用 -->
<bean id="testRmiService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl">
<value>rmi://127.0.0.1:9400/remoteService</value>
</property>
<property name="serviceInterface">
<value>com.cayden.rmi.IRmiServer<<value>
</property>
</bean>
</beans>
- 调用
public class TestRmi {
public static void main(String[] arg) {
System.out.println("rmi客户端开始调用");
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IRmiServer rmi=(IRmiServer)ctx.getBean("testRmiService");
rmi.test();
System.out.println("rmi客户端调用结束");
}
}