利用Spring來實現RMI,不用實現remote接口,也不用調用rmic編譯stub和skeleton,
服務端可以定義org.springframework.remoting.rmi.RmiServiceExporter類完成RMI服務器實現.
客戶端只要定義org.springframework.remoting.rmi.RmiProxyFactoryBean,告知rmi的url和接口
服務器實現:
接口:
IHello.java
package com.callan.Test;
public interface IHello {
public String hello(String name);
}
HelloImp.java
package com.callan.Test;
public class HelloImp implements IHello{
public String hello(String name){
return "hello:" + name;
}
}
服務端spring的配置:
<?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="helloService" class="com.callan.Test.HelloImp"/>
<bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service">
<ref bean="helloService"/>
</property>
<!-- 定義服務名 -->
<property name="serviceName">
<value>hello</value>
</property>
<property name="serviceInterface">
<value>com.callan.Test.IHello</value>
</property>
<property name="registryPort">
<value>8888</value>
</property>
</bean>
</beans>
客戶端:
必須把服務端的IHello.class文件放到客戶端一份
接下來看看客戶端要如何實作,只要透過org.springframework.remoting.rmi.RmiProxyFactoryBean,並告知服務的URL、代理的接口即可,就好像在使用本地端管理的服務一樣:
<?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.0.xsd">
<bean id="serviceClient"
class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceInterface">
<value>com.callan.Test.IHello</value>
</property>
<!-- serviceUrl以rmi開頭,定義服務器地址與端口和服務名 -->
<property name="serviceUrl">
<value>rmi://localhost:8888/hello</value>
</property>
</bean>
</beans>
客戶端的調用
package com.callan.Test;
import org.springframework.context.ApplicationContext;
org.springframework.context.support.ClassPathXmlApplicationContext
public class RMIClient {
public static void main(String[] args) {
ApplicationContext content = new new ClassPathXmlApplicationContext("com/config/applicationContext.xml");
IHello iHello = (IHello)content.getBean("serviceClient");
System.out.println(iHello.hello("callan"));
}
}