最近在搞Quartz任务监控管理,碰到了jmx,后来发现Quartz对jmx的支持不是很好,介绍的文档也比较少,另外Quartz可以很方便的支持rmi于是就看了一下rmi。下面把写的一些测试小例子附上,以便日后查看或者帮助他人。
IRmiService接口,是要暴露到远程的接口。
package rmi.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
//此为远程对象调用的接口,必须继承Remote类
public interface IRmiService extends Remote {
public String doSomething() throws RemoteException;
}
RmiServiceImpl实现IRmiService接口,实现具体的方法。
package rmi.serviceImpl;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import rmi.service.IRmiService;
//此为远程对象的实现类,须继承UnicastRemoteObject
public class RmiServiceImpl extends UnicastRemoteObject implements IRmiService {
private static final long serialVersionUID = 1L;
public RmiServiceImpl() throws RemoteException {
super();
}
@Override
public String doSomething() throws RemoteException {
System.out.println("doSomething is running...");
return "success msg";
}
}
RmiServer为服务端
package rmi.remotingservice;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import rmi.service.*;
import rmi.serviceImpl.*;
public class RmiServer {
public static void main(String[] args) {
try {
IRmiService personService = new RmiServiceImpl();
// 注册通讯端口
LocateRegistry.createRegistry(6600);
// 注册通讯路径
Naming.rebind("rmi://127.0.0.1:6600/rmiService", personService);
System.out.println("Service Start!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
RmiClient为客户端。
package rmi.remotingclient;
import java.rmi.Naming;
import rmi.service.IRmiService;
public class RmiClient {
public static void main(String[] args) {
try {
// 调用远程对象,注意RMI路径与接口必须与服务器配置一致
IRmiService personService = (IRmiService) Naming.lookup("rmi://127.0.0.1:6600/rmiService");
String msg = personService.doSomething();
System.out.println(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
RmiClient和RmiServer分别在不同的工程里运行。
源码下载地址:http://pan.baidu.com/s/1eRTgMNg