Spring中RMI的调用

来源:互联网 发布:西点文案策划 知乎 编辑:程序博客网 时间:2024/04/28 20:16


             以前写过java中RMI的调用:http://blog.csdn.net/drift_away/article/details/7347441,这次写的是利用Spring来实现RMI的功能:


利用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;  import org.springframework.context.support.FileSystemXmlApplicationContext;    public class RMIClient {        public static void main(String[] args) {          ApplicationContext content = new FileSystemXmlApplicationContext("E:/workspace/rmiClient/src/applicationContext.xml");                    IHello iHello = (IHello)content.getBean("serviceClient");                    System.out.println(iHello.hello("callan"));      }  }


参考资料:http://callan.iteye.com/blog/162756


原创粉丝点击