在Spring整合Rmi中:
服务端使用了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特有的,基于流的协议。
下面给出简单例子
1、服务端程序:
1)新建接口:
1public interface IRmiServer { 2 public boolean test(); 3}
- 1
- 2
- 3
2)实现该接口的方法:
1public class RmiServerImpl implements IRmiServer { 2 @Override 3 public boolean test() { 4 System.out.println("调用了我--服务端 O(∩_∩)O哈!"); 5 return true; 6 } 7}
3)在src下新建applicationContext.xml 配置文件
1<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.5//EN" "file:/usr/local/tomcat_report/lib/spring-beans-2.0.dtd"> 2<beans> 3 <!-- rmi --> 4 <bean id="rmiService" class="com.lovoo.rmi.impl.RmiServerImpl"> 5 </bean> 6 <bean id="remoteRmiService" class="org.springframework.remoting.rmi.RmiServiceExporter"> 7 <property name="serviceName"> 8 <value>remoteService</value> 9 </property> 10 <property name="service" ref="rmiService" /> 11 <property name="serviceInterface"> 12 <value>com.cayden.rmi.IRmiServer</value> 13 </property> 14 <property name="registryPort"> 15 <value>9400</value> 16 </property> 17 <property name="servicePort"> 18 <value>9401</value> 19 </property> 20 </bean> 21</beans>
4)启动服务端的类【MainServer.java】
1public class MainServer { 2 public static void main(String[] args) { 3 // TODO Auto-generated method stub 4 System.out.println("rmi服务端启动"); 5 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 6 System.out.println("rmi服务端启动完成。。。"); 7 } 8 9}
2、客户端代码:
1)在客户端使用服务端的接口文件:
1public interface IRmiServer { 2 public boolean test(); 3}
- 1
- 2
- 3
2)然后在src下新建【applicationContext.xml】
1<beans> 2 <!-- rmi远程调用 --> 3 <bean id="testRmiService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> 4 <property name="serviceUrl"> 5 <value>rmi://127.0.0.1:9400/remoteService</value> 6 </property> 7 <property name="serviceInterface"> 8 <value>com.lovoo.rmi.IRmiServer</value> 9 </property> 10 </bean> 11</beans>
3)最新新建客户端的测试类【TestRmi.java】
1public class TestRmi { 2 public static void main(String[] arg) { 3 System.out.println("rmi客户端开始调用"); 4 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 5 IRmiServer rmi=(IRmiServer)ctx.getBean("testRmiService"); 6 rmi.test(); 7 System.out.println("rmi客户端调用结束"); 8 } 9}