提供RMI服务的接口类
package cn.yw.service;
public interface MessageService {
public String getMessage();
}
提供RMI服务的类
package cn.yw.service.impl;
import cn.yw.service.MessageService;
public class MessageServiceImpl implements MessageService{
public String getMessage() {
return "hello world!";
}
}
在spring中使用RmiServiceExporter注册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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="messageService" class="cn.yw.service.impl.MessageServiceImpl"/>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<!-- 该属性表示提供RMI服务的类 -->
<property name="service">
<ref bean="messageService"/>
</property>
<!-- 该属性表示RMI服务名 -->
<property name="serviceName">
<value>MessageService</value>
</property>
<!-- 该属性表示RMI服务接口名 -->
<property name="serviceInterface">
<value>cn.yw.service.MessageService</value>
</property>
<!-- 该属性表示RMI服务端口 -->
<property name="registryPort">
<value>9999</value>
</property>
</bean>
</beans>
在spring中使用通过RmiProxyFactoryBean类调用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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="messageServiceClient" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl">
<!-- url=rmi://{host}:端口/服务名 -->
<value>rmi://localhost:9999/MessageService</value>
</property>
<property name="serviceInterface">
<value>cn.yw.service.MessageService</value>
</property>
</bean>
</beans>
在使用RMI服务时首先要打开RMI服务,打开RMI服务的代码如何,即要先运行如下代码
package cn.yw.rmi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class RMIserver {
public static void main(String args[]){
ApplicationContext context=new FileSystemXmlApplicationContext("WebRoot/WEB-INF/rmi.xml");
System.out.println("server start...");
}
}
客户端调用RMI服务的代码,在服务运行的情况下运行客户端代码会得到你所要的结果
package cn.yw.rmi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import cn.yw.service.MessageService;
public class TestRMI {
public static void main(String args[]){
ApplicationContext context=new FileSystemXmlApplicationContext("WebRoot/WEB-INF/rmiclient.xml");
MessageService ms=(MessageService)context.getBean("messageServiceClient");
System.out.println(ms.getMessage());
}
}
该案例的完整代码下载地址:http://download.youkuaiyun.com/detail/lishamao/4164394