Python微信订餐小程序课程视频
https://edu.csdn.net/course/detail/36074
Python实战量化交易理财系统
https://edu.csdn.net/course/detail/35475
自己简单写了个Java RMI(远程方法调用)的实现案例。
为了更好理解RMI(远程方法调用)、序列化的意义等等,花费三天多的时间肝了一个Java RMI的实现案例。
!!!高能预警!!!
代码量有点大,先附上了简图用于理解
整个过程分为两大步
- 第一步–注册过程:客户端通过指定路由获取注册中心指定的远程客户端对象;
- 第二部–服务调用过程:客户端通过远程客户端对象访问远程服务端(代理服务)从而访问到真实服务的实现
调整为舒适的姿势,慢慢看…… 废话少说,上代码!!!
1.定义远程标记接口
面向接口编程,具体作用看后面的代码怎么使用
// 标记接口:直接或间接实现MyRMI接口将获得远程调用的能力
public interface MyRMI{
}
2.编写RMI 服务注册中心
注册中心类:用于注册服务和获取服务,核心是hashMap路由表对象
/**
* 注册中心:维护服务发布的注册表
*/
public class MyRMIRegistry {
// 默认端口
public final int REGISTRY\_PORT = 10099;
private String host;
private int port;
private Map bindings;
public MyRMIRegistry(int port){
this.port = port;
}
public MyRMIRegistry(String host, int port){
this.host=host;
this.port=port;
}
public void createRegistry(String serverName,MyRMI myRMI){
// 注册服务,并开启服务
this.bindings = new HashMap<>();
String host = null;
try {
host = Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
// 路由规则可自行定义,只要能确保Key唯一即可
String binding = "myrmi://"+host+":"+port+"/"+serverName;
this.bindings.put("myrmi://"+host+":"+port+"/"+serverName,myRMI);
System.out.println("注册的服务有:"+bindings.keySet().toString());
MyRMIRegistryServer myRMIRegistryServer = new MyRMIRegistryServer(this.port, this.bindings);
Executors.newCachedThreadPool().submit(myRMIRegistryServer); // 线程池启动服务
}
public MyRMI getRegistry(String serverName){
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
MyRMI myRMI = null;
// 通过
try {
socket = new Socket(host, port);
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject("myrmi://"+host+":"+port+"/"+serverName);
in = new ObjectInputStream(socket.getInputStream());
myRMI = (MyRMI)in.readObject();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
return myRMI;
}
}