在Spring中配置RMI服务
在服务端,RmiServiceExporter可以将任意一个Spring管理的Bean发布为RMI服务。
在客户端,Spring的RmiProxyFactoryBean是一个工厂Bean,可以为RMI服务创建代理。RmiProxyFactoryBean生成一个代理对象,负责客户端与远程的RMI服务进行通信。
服务端发布RMI服务
package com.x.rmi; public interface HelloService { public String sayHello(String name); }
package com.x.rmi; public class HelloServiceImpl implements HelloService { public String sayHello(String name) { System.out.println("Hello " + name); return "Hello " + name; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="service" ref="helloService"></property> <property name="serviceName" value="HelloService"></property> <property name="serviceInterface" value="com.x.rmi.HelloService"></property> </bean> <bean id="helloService" class="com.x.rmi.HelloServiceImpl" /> </beans>
这里把helloService Bean装配进service属性中来表明RmiServiceExporter要将该Bean发布为一个RMI服务。
serviceName属性命名了RMI服务。
serviceInterface属性指定了此服务所实现的接口。
package com.x.rmi; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RmiServer { public static void main(String[] args) throws InterruptedException { new ClassPathXmlApplicationContext("com/x/rmi/remote-server.xml"); } }
客户端调用RMI服务
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="helloService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl" value="rmi://localhost/HelloService"></property> <property name="serviceInterface" value="com.x.rmi.HelloService"></property> </bean> </beans>
package com.x.rmi; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RmiClient { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/x/rmi/remote-client.xml"); HelloService helloService = (HelloService) ctx.getBean("helloService"); String ret = helloService.sayHello("Rod Johnson"); System.out.println(ret); } }