Spring RMI的应用

本文介绍如何使用Spring框架实现RMI服务,无需手动实现远程接口或编译stub和skeleton。通过配置服务端的RmiServiceExporter和客户端的RmiProxyFactoryBean,简化了RMI服务的部署和调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用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"));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值