spring rmi简单实例

来源:互联网 发布:数组 高级 excel 编辑:程序博客网 时间:2024/05/20 11:23

      

有时候系统为了方便于后面的拆分和多服务部署,需要提前设想好不同服务之间如何调用。大多数使用http请求即可解决服务之间互相调用的问题,速度也有保证。不过也有服务之间调用接口(非http请求而是直接调用另一个服务的service接口)的情况,这个时候就需要远程调用了(因为没有办法直接调用)。

闲暇之余研究了下spring的rmi技术。spring的rmi是将java的核心类使用方法进行了封装,达到了可以完全配置化,只要几条配置语句就可以实现服务端rmi注册;客户端再直接得到对应的bean,就可以直接使用service定义的方法了。

首先是服务端spring的配置文件:

<!-- goods info service --><bean id="goodsServiceImpl" class="com.goods.service.impl.GoodsServiceImpl" /><bean id="goodsServiceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter"><property name="service" ref="goodsServiceImpl" /><!-- 定义服务名 --><property name="serviceName" value="goodsService" /><property name="serviceInterface" value="com.goods.service.GoodsService" /><property name="registryPort" value="8091" /></bean>
其中第一个bean定义了接口实现类的bean,

org.springframework.remoting.rmi.RmiServiceExporter
是spring的RMI实现类:serviceName为注册的接口名称,serviceInterface为接口类,service为接口实现类(对应上面定义的bean),registryPort为注册的服务器端口。

然后是客户端配置文件:

<!-- goods info service --><bean id="goodsService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"><property name="serviceUrl" value="rmi://192.168.1.1:8091/goodsService" /><property name="serviceInterface" value="com.goods.service.GoodsService" /></bean>
其中

org.springframework.remoting.rmi.RmiProxyFactoryBean
为spring的RMI客户端工厂类:serviceUrl为rmi接口链接,需要ip、端口和接口名,serviceInterface为暴露的接口类

这样就配置完成了,当服务端启动之后,客户端去读取客户端配置文件得到RMI工厂bean,则可以直接调用GoodsService接口里面的方法了。

需要注意的是spring容器的概念,如果这两个配置文件都在同一个工程内,那么就是同一个spring容器中可能有两个GoodsServiceImpl的bean,这样如果这个bean有类里面调用了则会报错,因为spring不知道其调用的哪个bean。


待续~~~



0 0
原创粉丝点击