好久没有写java代码了,最近工作项目上需要做一个java后台的程序,此后台程序提供start(), stop()和status()接口,分别用于启动、关闭和得到状态信息。
参照以前的项目代码,做这种后台的程序可以采用RMI,即在某端口上启动server,通过RMI使用客户端(当然,这种服务端和客户端实际上在同一台机器上)来调用服务端的方法。
老早以前看过spring对RMI的支持大大简化了工作,那么就用这个吧。
Spring RMI支持大致方法如下:
1. 先创建一个Server接口
package cn.lettoo.rmi.server; public interface IService { String say(); }
2. 这个接口提供一个say()的方法,下面写一个这个接口的实现类
package cn.lettoo.rmi.server; public class ServiceImpl implements IService { private int i = 0; @Override public String say() { i ++; return String.format("This is %d times to say something.", i); } }
接口实现也非常简单,就是打印一句话,告诉调用者这是第多少次调用了。
3. 接下来,通过spring bean定义一个RmiServiceExporter,这个xml为server.xml
4. 然后,写一个RunServer类来启动这个server
package cn.lettoo.rmi.server; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RunServer { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "server.xml"}); } }
5. 现在,server已经启动起来了,它在localhost:1199上面启动了一个MyService的服务,接下来,使用spring bean来创建一个serviceProxy,作为客户端。这个xml为client.xml
6. 再写一个RunClient来启动一个client来调用server的方法吧
package cn.lettoo.rmi.client; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.lettoo.rmi.server.IService; public class RunClient { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client.xml"}); IService service = (IService)context.getBean("serviceProxy"); //调用两次 System.out.println(service.say()); System.out.println(service.say()); } }
就这么简单,项目文件结构如下图,需要加spring.jar和apache 的common-logging.jar,并把conf目录和jar包放到build path中
运行RunClient(注意,先要把RunServer运行起来)结果如下:
This is 1 times to say something.
This is 2 times to say something.
再运行一次:
This is 3 times to say something.
This is 4 times to say something.