远程调用 - spring+rmi
远程方法调用(RMI)。通过使用RmiProxyFactoryBean和RmiServiceExporter,Spring支持传统的RMI(使用java.rmi.Remote interfaces 和 java.rmi.RemoteException)和通过RMI调用器(可以使用任何Java接口)的透明远程调用。
一,服务端:
1,服务端接口方法
/**
* 服务端的接口方法
* @author hwt
*
*/
public interface RmiService {
public String sayHello();
public String getUserInfo(User user);
}
2,实体类(要序列化)
/**
* 要序列化
* @author hwt
*/
public class User implements Serializable {
private static final long serialVersionUID = 3797175825569039103L;
private String userName;
private int age;
public User(String userName,int age) {
this.userName = userName;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3,服务端接口实现方法
/**
* 服务端接口方法实现类
* @author hwt
*
*/
public class RmiServiceImpl implements RmiService {
@Override
public String sayHello() {
return "hello,world! I'm ServerRmi!";
}
@Override
public String getUserInfo(User user) {
return "姓名:"+user.getUserName()+";年龄:"+user.getAge();
}
}
4,配置文件
<bean id="rmiServiceImpl" class="testrmi.RmiServiceImpl"></bean>
<!-- 配置服务端的rmi -->
<bean id="rmiServer" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName">
<!-- 对应着客户端的serviceUrl=rmi://192.183.3.205:1200/rmiServer -->
<value>rmiServer</value>
</property>
<property name="service" ref="rmiServiceImpl"/>
<property name="serviceInterface">
<value>testrmi.RmiService</value>
</property>
<!-- 注册端口 -->
<property name="registryPort" value="1200"/>
</bean>
5,测试方法
public class Test {
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
//这里是要注入的是服务器端的实现类,不是配置的服务的rmi的RmiServiceExporter
RmiService rmiServer = (RmiService) act.getBean("rmiServiceImpl");
System.out.println("RMI服务端已经启动....");
}
}
二,客户端
1,将服务端的RmiService 接口和 User打包成jar包,并导入到客户端的项目中,方便客户端调用
2.客户端配置文件
<bean id="rmiClient" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://192.183.3.205:1200/rmiServer"></property>
<property name="serviceInterface" value="testrmi.RmiService"></property>
<property name="lookupStubOnStartup" value="false"/>
<property name="refreshStubOnConnectFailure" value="true"/>
<property name="cacheStub" value="false"/>
</bean>
3,客户端测试
public class RmiClient {
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
RmiService rmiService = (RmiService) act.getBean("rmiClient");
//调用服务端接口方法
System.out.println(rmiService.sayHello());
System.out.println("==================");
User user = new User("黄文韬",24);
System.out.println(rmiService.getUserInfo(user));
}
}