Spring整合 RMI
Spring整合RMI的原理
客户端的核心是RmiProxyFactoryBean,包含serviceURL属性和serviceInterface属性。
通过JRMP访问服务。JRMP JRMP:java remote method protocol,Java特有的,基于流的协议。
?
?
服务端暴露远程服务
RmiServiceExporter把任何Spring管理的Bean输出成一个RMI服务。通过把Bean包装在一个适配器类中工作。适配器类被绑定到RMI注册表中,并且将请求代理给服务类。
?
?
?
服务端程序:
1 IHelloWorld.java POJO的接口
01.public interface IHelloWorld { 02. public String helloWorld(); 03. 04. public String sayHelloToSomeBody(String someBodyName); 05.}
?
2 HelloWorld.java POJO的实现
01.public class HelloWorld implements IHelloWorld { 02. 03. @Override 04. public String helloWorld() { 05. return "Hello World!"; 06. } 07. 08. @Override 09. public String sayHelloToSomeBody(String someBodyName) { 10. return "Hello World!" + someBodyName; 11. } 12. 13.}
?
3 spring配置文件rmi_server_context.xml
01.<?xml version="1.0" encoding="UTF-8"?> 02.<beans xmlns="http://www.springframework.org/schema/beans" 03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 04. xmlns:tx="http://www.springframework.org/schema/tx" 05. xsi:schemaLocation="http://www.springframework.org/schema/beans 06.http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 07.http://www.springframework.org/schema/aop 08.http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 09.http://www.springframework.org/schema/tx 10.http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 11. 12. <bean id="helloWorld" /> 13. 14. <bean id="serviceExporter" ref="helloWorld" /> 16. <!-- 定义服务名 --> 17. <property name="serviceName" value="hello" /> 18. <property name="serviceInterface" value="springapp.rmi.rmi.IHelloWorld" /> 19. <property name="registryPort" value="8088" /> 20. </bean> 21. 22.</beans>
?
4? 服务端启动RMI的代码HelloHost.java
01.public class HelloHost { 02. public static void main(String[] args) { 03. ApplicationContext ctx = new ClassPathXmlApplicationContext( 04. "rmi_server_context.xml"); 05. System.out.println("RMI服务伴随Spring的启动而启动了....."); 06. } 07.}
?
客户端
1 配置文件rmi_client_context.xml
01.<?xml version="1.0" encoding="UTF-8"?> 02.<beans xmlns="http://www.springframework.org/schema/beans" 03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 04. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> 05. <bean id="helloWorld" value="rmi://10.87.40.141:8088/hello" /> 07. <property name="serviceInterface" value="springapp.rmi.rmi.IHelloWorld" /> 08. </bean> 09.</beans>
?
2 客户端代码 HelloClient.java
01.public class HelloClient { 02. 03. public static void main(String[] args) throws RemoteException { 04. ApplicationContext ctx = new ClassPathXmlApplicationContext( 05. "rmi_client_context.xml"); 06. IHelloWorld hs = (IHelloWorld) ctx.getBean("helloWorld"); 07. System.out.println(hs.helloWorld()); 08. System.out.println(hs.sayHelloToSomeBody("Lavasoft")); 09. } 10. 11.}
?