当我们的web系统很大的时候,我们就需要使用分布式框架
分布式框架都用到了RPC
可以让客户端像调用本地服务一样调用远程服务
其本质是通过Socket链接服务端, 然后向服务端发送需要调用的服务的接口
然后服务端向客户端返回实现了接口的对象
客户端就直接调用了
我们看一下最终效果
IStudent invokeServer = new ServerInvoker<IStudent>().getInvokeServer(IStudent.class, "localhost", 9999);
invokeServer.ml();
接下来我们看一下服务类
服务类有两个主方法 注册和启动
首先我们需要将接口的对象保存到容器中
private void inflate(Map<Class,Object> container,File file) throws Exception {
if(file!=null&&file.isFile()){
if(file.getName().endsWith(".java")){
Class<?> aClass = Class.forName(getClassName(file.getAbsolutePath()));
if(aClass.isInterface())
return;
Object o = aClass.newInstance();
container.put(Class.forName(getClassName(file.getAbsolutePath())), o);
//还要将接口和实现类的映射关系放到map
for(Class c:aClass.getInterfaces()){
container.put(Class.forName(c.getName()),o);
}
}
}
//如果是文件夹,递归调用
if(file!=null&&file.isDirectory()){
for(File f:file.listFiles()){
inflate(container,f);
}
}
}
然后启动服务
//开启服务,接受客户端的服务调用
public void start(int port) {
try {
ServerSocket serverSocket=new ServerSocket(port);
System.out.println("服务端已经开启了");
while(true){
Socket accept = serverSocket.accept();
InputStream is = accept.getInputStream();
OutputStream outputStream = accept.getOutputStream();
ObjectInputStream objectInputStream=new ObjectInputStream(is);
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
System.out.println("收到客户端的服务调用请求");
Object o = objectInputStream.readObject();
System.out.println(o);
//给客户端写入
objectOutputStream.writeObject(container.get(o));
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
服务启动后就等客户端来调用了
//从远程服务获得对象
public T getInvokeServer(Class c,String address,int port) throws IOException, ClassNotFoundException {
Socket socket=new Socket(address,port);
String name = c.getName();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
System.out.println("客户端向服务端发送请求调用服务");
objectOutputStream.writeObject(c);
ObjectInputStream objectInputStream=new ObjectInputStream(socket.getInputStream());
return (T) objectInputStream.readObject();
}
完整代码可以去我的GitHub