Spring框架中已經很好地整合了RMI技術,只需要做一些簡單的配置就可以了,RMI中的註冊發佈都不需要我們做了。
服務端:
接口(不需要繼承Remote):
public interface RyxxglInterfaces { public String list(); }
接口的實現(不需要拋出RemoteException):
public class RyxxglInterfacesImpl implements RyxxglInterfaces{ public String list(){ // TODO Auto-generated method stub System.out.println("start..."); return "aaa"; } }
applicationContext-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="ryxxglService" class="com.jframe.web.xtgl.ryxxgl.rmi.RyxxglInterfacesImpl" /> <bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="service" ref="ryxxglService" /> <!-- 定義服務名 --> <property name="serviceName" value="ryxxgl" /> <property name="serviceInterface" value="com.jframe.web.xtgl.ryxxgl.rmi.RyxxglInterfaces" /> <property name="registryPort" value="8088" /> </bean> </beans>
客戶端:
客戶端也使用Spring來整合,導入接口的jar包
applicationContext-rmi-client.xml配置文件:
<?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-2.5.xsd"> <bean id="ryxxglService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl" value="rmi://127.0.0.1:8088/ryxxgl"/> <property name="serviceInterface" value="com.jframe.web.xtgl.ryxxgl.rmi.RyxxglInterfaces"/> </bean> <bean id="ryxxglServiceClient" class="com.jframe.web.xtgl.ryxxgl.rmi.RyxxglClientImpl"> <property name="ryxxglService" ref="ryxxglService"/> </bean> </beans>
客戶端測試類:
import java.rmi.RemoteException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RyxxglClientImpl { private RyxxglInterfaces ryxxglService; public static void main(String[] args) throws RemoteException { ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext-rmi-client.xml"); RyxxglInterfaces hs = (RyxxglInterfaces) ctx.getBean("ryxxglService"); System.out.println(hs.list()); } public RyxxglInterfaces getRyxxglService() { return ryxxglService; } public void setRyxxglService(RyxxglInterfaces ryxxglService) { this.ryxxglService = ryxxglService; } }