透过org.springframework.remoting.rmi.RmiServiceExporter,Spring 简化了这些手续,来实际看看例子,了解Spring在RMI上的使用与简化,首先定义服务对象的接口: ISomeService.java package onlyfun.caterpillar; public interface ISomeService { public String doSomeService(String some); public void doOtherService(int other); } 可以看到服务对象的接口不用继承java.rmi.Remote界面,而在实作时也不用继承java.rmi.UnicastRemoteObject,例如: SomeServiceImpl.java package onlyfun.caterpillar; public class SomeServiceImpl implements ISomeService { public String doSomeService(String some) { return some + " is processed"; }
public void doOtherService(int other) { // bla.. bla } } 接下来在伺服端,您只要在Bean定义档中定义,让Spring管理、生成Bean,即可注册、启动RMI服务,例如:rmi-server.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www./dtd/spring-beans.dtd"> <beans> <bean id="someService" class="onlyfun.caterpillar.SomeServiceImpl"/> <bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="service"> <ref bean="someService"/> </property> <property name="serviceName"> <value>SomeService</value> </property> <property name="serviceInterface"> <value>onlyfun.caterpillar.ISomeService</value> </property> </bean>
</beans> 很简单,只要告诉org.springframework.remoting.rmi.RmiServiceExporter服务对象、名称与要代理的接口,之后Spring读取完定义文件并生成Bean实例后,RMI服务就会启动。 接下来看看客户端要如何实作,只要透过org.springframework.remoting.rmi.RmiProxyFactoryBean,并告知服务的URL、代理的接口即可,就好像在使用本地端管理的服务一样,例如Bean定义档可以如下撰写: rmi-client.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www./dtd/spring-beans.dtd"> <beans> <bean id="someServiceProxy" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl"> <value>rmi://localhost/SomeService</value> </property> <property name="serviceInterface"> <value>onlyfun.caterpillar.ISomeService</value> </property> </bean> </beans> 以下是个简单的客户端呼叫远程服务的例子: .... ApplicationContext context = new FileSystemXmlApplicationContext("rmi-client.xml"); ISomeService service = (ISomeService) context.getBean("someServiceProxy"); String result = service.doSomeService("Some request"); System.out.println(result); .... 一些相关的介绍: |
|