在Spring环境使用RMI时,可以省略以下几点:
1、接口类不需要继承Remote,方法不需要抛出RemoteException异常对象。
2、实现类不需要继承UnicastRemoteObject。
3、RMI服务自动注册。
下面通过具体的例子来说明其用法。
一、导出RMI服务
1、bean的配置
Xml代码
- <beans>
- <bean id="syncServiceImpl" class="com.cjm.service.rmi.SyncServiceImpl" />
- <bean id="syncServiceProxy" class="com.cjm.service.rmi.SyncServiceRMIExporter">
- <property name="service">
- <ref bean="syncServiceImpl" />
- < span>property>
- <property name="serviceName">
- <value>hawkeyeService< span>value>
- < span>property>
- <property name="serviceInterface">
- <value>com.cjm.service.rmi.SyncService< span>value>
- < span>property>
- <property name="servicePort">
- <value>1099< span>value>
- < span>property>
- <property name="registryPort">
- <value>1099< span>value>
- < span>property>
- < span>bean>
- < span>beans>
2、类源码
Java代码
- public class SyncServiceRMIExporter extends RmiServiceExporter{
- public SyncServiceRMIExporter() {
- //通过系统属性设置RMI的hostname
- System.setProperty("java.rmi.server.hostname", "localhost");
- }
- }
Java代码
- //RMI服务接口类
- public interface SyncService{
- public boolean updateMonicaSiInfos(String oldInfo, String newInfo);
- }
Java代码
- public class SyncServiceImpl implements SyncService {
- @Override
- public boolean updateMonicaSiInfos(String oldInfo, String newInfo) {
- oldInfo = StringUtils.trimToEmpty(oldInfo);
- newInfo = StringUtils.trimToEmpty(newInfo);
- if (StringUtils.isEmpty(newInfo)) {
- return false;
- }
- ......
- logger.warn("成功: oldInfo=" + oldInfo + ", newInfo=" + newInfo);
- return true;
- }
- }
二、调用RMI服务
1、bean的配置
Xml代码
- <beans>
- <bean id="serviceImpl" class="RMIServiceImpl">
- <property name="syncService" ref="hawkeyeService"/>
- < span>bean>
- <bean id="hawkeyeService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
- <property name="serviceUrl">
- <value>rmi://localhost:1099/hawkeyeService< span>value>
- < span>property>
- <property name="serviceInterface">
- <value>com.cjm.service.rmi.SyncService< span>value>
- < span>property>
- < span>bean>
- < span>beans>
2、类源码
Java代码
- public class RMIServiceImpl {
- private SyncService syncService;
- public SyncService getSyncService() {
- return syncService;
- }
- public void setSyncService(SyncService syncService) {
- this.syncService = syncService;
- }
- public void doAction(String oldValue, String newValue)throws Exception{
- boolean b = syncService.updateMonicaSiInfos(oldValue, newValue);
- if(b){
- System.out.println("RMI调用成功");
- }else{
- System.out.println("RMI调用失败");
- }
- }
- }