二、Spring 封装RMI实现 Spring RMI中,主要有两个类:org.springframework.remoting.rmi.RmiServiceExporter和org.springframework.remoting.rmi.RmiProxyFactoryBean 服务端使用RmiServiceExporter暴露RMI远程方法,客户端用RmiProxyFactoryBean间接调用远程方法。
首先,也是两个工程,服务端用Web工程,因为使用Spring,我们依托Web容器来完成。 1、在该服务端Web工程中添加接口,普通接口,无需继承其他 [html] view plain copy
- package rmi.test;
-
- public interface HelloRMIService {
-
- public int getAdd(int a, int b);
-
-
- }
2、接口的实现类 [html] view plain copy
- package rmi.test;
-
- public class HelloRMIServiceImpl implements HelloRMIService {
-
- @Override
- public int getAdd(int a, int b) {
-
- return a+b;
- }
-
- }
3、在该服务端Web工程中添加Spring的bean配置文件,比如命名为rmiServer.xml,内容如下:
[html] view plain copy
说明:这里不详细的说明了,主要配置了真实实现类,用RmiServiceExporter暴露时,配置property要注意的有service,serviceName,serviceInterface,端口registryPort。 启动Web工程的服务器,该配置文件应该被Spring的监听器监听,并加载,启动成功后,服务端就算建好了。如果服务器是在localhost启动的,那么暴露的RMI的IP也是localhost,如果需要使用其他IP,需要让服务器在其他的IP启动。 这里没有web服务器,使用main模拟启动,如下: [html] view plain copy
- package rmi.test;
-
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class RMIServiceTest {
-
- public static void main(String[] args) {
-
- new ClassPathXmlApplicationContext("rmiServer.xml");
-
- }
-
- }
客户端调用:为了方便也只新建一个简单的Java Project,使用静态的java代码来调用了。
1、 在源文件src下建立一个rmiClient.xml [html] view plain copy
这里注意到RmiProxyFactoryBean的两个重要的property:serviceUrl和serviceInterface,HelloRMIService接口可以从服务端的接口打成jar包来提供。
2、 新建java类 [html] view plain copy
- package rmi.test;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class RMIClient {
-
- public static void main(String[] args) {
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext("rmi/test/rmiClient.xml");
- HelloRMIService helloRMIService = applicationContext.getBean("myRMIClient",HelloRMIService.class);
- System.out.println(helloRMIService.getAdd(3, 4));
- }
-
- }
运行,成功!好了,这就是一个采用Spring封装的RMI的例子,项目工作中应该经常使用的。有什么问题,欢迎讨论交流。
|