spring整合RMI

<script>function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>

RMI是从JDK 1.1开始就出现的API功能,它让客户端在使用远程对象所提供的服务时,就如何使用本地对象一样,然而RMI在使用时必须一连串繁复的手续,像是服务介 面在定义时必须继承java.rmi.Remote接口、服务Server在实作时必须继承java.rmi.UnicastRemoteObject 别、必须使用rmic产生stubskeleton等等。

透过org.springframework.remoting.rmi.RmiServiceExporterSpring 简化了这些手续,来实际看看例子,了解SpringRMI上的使用与简化,首先定义服务对象的接口:

  •  

    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.springframework.org/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.springframework.org/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);
....

 

 

你可能感兴趣的:(spring,jdk,xml,bean)