客户端和服务器端必须是纯Java实现。RMI服务是典型的面向接口编程,只有在远程接口里定义的方法才会作为远程服务,远程方法的返回值和参数都必须实现Serializable接口,因为远程在网络上传输只能传输字节流,因此,要求参数、返回值都可以转换成字节流-即实现序列化。
如果要暴露远程方法,Spring提供了RmiServiceExporter类,该类可以将一个普通Bean实例绑定成远程服务。将普通bean实例绑定为远程服务的完整配置如下(服务器端配置server.xml):
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<!-- 该属性表示提供服务的类 -->
<property name="service">
<ref bean="userService"/>
</property>
<!-- 该属性表示服务名 -->
<property name="serviceName">
<value>userService</value>
</property>
<!-- 该属性表示服务接口名 -->
<property name="serviceInterface">
<value>com.sdj.core.service.IUserService</value>
</property>
<!-- 该属性表示服务端口 -->
<property name="registryPort">
<value>9999</value>
</property>
</bean>
客户端配置如下client.xml:
<bean id="userServiceClient" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl">
<!-- url=rmi://{host}:端口/服务名 -->
<value>rmi://localhost:9999/userService</value>
</property>
<property name="serviceInterface">
<value>com.sdj.core.service.IUserService</value>
</property>
</bean>
首先启动服务器端,代码如下:
public class RMIServer {
public static void main(String args[]){
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:server.xml");
System.out.println("server start...");
}
}
服务器端启动后,即注册了服务userService,此时客户端便可以远程调用userService,客户端代码如下:
public class RMIClient
{
/**
* @param args
*/
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:client.xml");
System.out.println(context);
IUserServiceservice = (IUserService)context.getBean("userServiceClient");
System.out.println(service.getUserByID(1));
}
}