发表于: 2017-08-10 22:46:06
1 894
今天完成的事:
听取师兄的建议,先学习一下Java RMI,
首先定义一个接口,必须继承Remote
public interface GetServer extends Remote {
Register get()throws RemoteException;
}
然后实现类必须继承UnicastRemoteObject
public class GetServiceImpl extends UnicastRemoteObject implements GetServer{
protected GetServiceImpl() throws RemoteException {
}
@Override
public String getAll() throws RemoteException {
return "aaaa";
}
}
然后创建一个远程对象并暴露端口8888
public class RmiTest {
public static void main(String []args) {
try {
//创建一个远程对象
GetServer getServer=new GetServiceImpl();
//远程主机远程对象注册表Registry的实例,并指定端口为8888,这一步必不可少(Java默认端口是1099),
// 必不可缺的一步,缺少注册表创建,则无法绑定对象到远程注册表上
LocateRegistry.createRegistry(8888);
//把远程对象注册到RMI注册服务器上,并命名为RHello
//绑定的URL标准格式为:rmi://host:port/name(其中协议名可以省略,下面两种写法都是正确的)
Naming.bind("rmi://localhost:8888/getServer",getServer);
//Naming.bind("//localhost:8888/RmiHello",rmiHello);
//必须捕获这三个异常,否则需要在main方法中抛出
} catch (RemoteException e) {
System.out.println("创建远程对象发生异常");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("URL畸形异常");
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println("重复绑定对象异常");
e.printStackTrace();
}
}
}
然后是客户端类
public class HelloClient {
public static void main(String []args) {
try {
//在RMI服务注册表中查找名称为RHello的对象,并调用其上的方法
GetServer getServer = (GetServer)Naming.lookup("rmi://localhost:8888/getServer");
System.out.println(getServer.get());
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
客户端也需要GetService接口
直接运行会各种报错,用命令行编译运行就没问题了,不知道为什么
启动Server后启动Client会获取到Server的getServer.get()方法,输出结果"aaaa"
想要传输对象就必须序列化对象
什么是序列化对象:
期间报了这个异常:
遇到的困难:
我尝试用javaRMI进行mysql的读写,但是失败了,报ClassNotFoundException,明天试试SpringRMI
收获:
稍微理解javaRMI
明天的计划:
学习SpringRMI
评论