RPC要解决的两个问题:
- 解决分布式系统中,服务之间的调用问题。
- 远程调用时,调用者不必知道服务端的实现逻辑,直接调用即可。
首先创建类RpcRequestModel,主要用来传递调用信息。该类需要实现Serializable接口,socket传输的时候可能需要序列化和反序列化。
package com.lh.spring.boot.zk.rpc;
import java.io.Serializable;
/**
* @description:请求模板类
* @author: lianghao
* @create: 2019-05-31 14:31
**/
public class RpcRequestModel implements Serializable {
private static final long serialVersionUID = -6709078275686233757L;
/**请求的类路径*/
private String className;
/**请求的方法名称*/
private String methodName;
/**请求参数数组*/
private Object[] params;
public RpcRequestModel(){
super();
}
public RpcRequestModel(String className, String methodName, Object[] params) {
this.className = className;
this.methodName = methodName;
this.params = params;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
}
创建测试服务的接口以及相关实现
package com.lh.spring.boot.zk.rpc;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 14:29
**/
public interface IHelloService {
String sayHello(String name);
}
package com.lh.spring.boot.zk.rpc;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 14:30
**/
public class HelloServiceImpl implements IHelloService{
@Override
public String sayHello(String name) {
return "hello,"+name;
}
}
创建服务端处理类,这里采用多线程的方式,主要就是通过socket读取调用信息,通过反射的方式,调用相关服务的方法,在通过socket返回
package com.lh.spring.boot.zk.rpc;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 14:38
**/
public class RpcServiceHandler implements Runnable {
/**数据传输的socket*/
private Socket socket;
/**获取的service类*/
private Object service;
/**覆盖无参构造方法,必须使用有参构造*/
public RpcServiceHandler(Socket socket, Object service) {
this.socket = socket;
this.service = service;
}
@Override
public void run() {
ObjectInputStream objectInputStream = null;
try {
/**通过socket获取对象输入流*/
objectInputStream = new ObjectInputStream(socket.getInputStream());
/**读取调用信息*/
RpcRequestModel rpcRequestModel = (RpcRequestModel) objectInputStream.readObject();
/**通过反射调用方法*/
Object object = invoke(rpcRequestModel);
/**通过socket获取对象输出流*/
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
/**输出调用结果*/
objectOutputStream.writeObject(object);
objectOutputStream.flush();
objectOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != objectInputStream){
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public Object invoke(RpcRequestModel rpcRequestModel) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Object[] params = rpcRequestModel.getParams();
Class[] paramsTypeArr = new Class[params.length];
for(int i = 0 ; i < params.length ; i++){
paramsTypeArr[i] = params[i].getClass();
}
Method method = service.getClass().getMethod(rpcRequestModel.getMethodName(),paramsTypeArr);
return method.invoke(service , params);
}
}
客户端请求Handler通过socket和服务端建立连接,然后通过socket调用服务端的socket
package com.lh.spring.boot.zk.rpc;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 14:58
**/
public class RpcTransportSocket {
private String host;
private int port;
public RpcTransportSocket(String host, int port) {
this.host = host;
this.port = port;
}
public Socket newSocket(){
System.out.println("准备建立socket连接...." + host + ",port:" + port);
Socket socket = null;
try {
socket = new Socket(host , port);
} catch (IOException e) {
throw new RuntimeException("Socket连接创建失败!host:" + host + ",port:" + port);
}
return socket;
}
public Object sendRequestSocket(RpcRequestModel rpcRequestModel){
Socket socket = null;
try {
/**获取一个socket*/
socket = newSocket();
/**通过socket获取输出流*/
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
/**通过socket输出请求信息*/
objectOutputStream.writeObject(rpcRequestModel);
objectOutputStream.flush();
/**通过socket获取输入流*/
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
/**通过socket读取调用返回数据*/
Object object = objectInputStream.readObject();
objectInputStream.close();
objectOutputStream.close();
return object;
}catch (Exception e){
e.printStackTrace();
}finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
服务端启动类,通过线程池的方式,来启动服务端进行监听调用。
package com.lh.spring.boot.zk.rpc;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @description: Rpc的服务端
* @author: lianghao
* @create: 2019-05-31 14:37
**/
public class RpcService {
public static final ExecutorService executor = Executors.newCachedThreadPool();
public void publisher(final Object object , int port){
/**启动服务监听*/
try(ServerSocket serverSocket = new ServerSocket(port)){
while (true){
/**获取一个监听的socket*/
Socket socket = serverSocket.accept();
executor.execute(new RpcServiceHandler(socket , object));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
动态代理类,通过动态代理模式来进行服务调用
package com.lh.spring.boot.zk.rpc;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @description: 动态代理类
* @author: lianghao
* @create: 2019-05-31 15:07
**/
public class RemoteInvocationHandler implements InvocationHandler {
private String host;
private int port;
public RemoteInvocationHandler(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
RpcRequestModel rpcRequestModel = new RpcRequestModel(method.getDeclaringClass().getName(), method.getName() , args);
RpcTransportSocket rpcTransportSocket = new RpcTransportSocket(host , port);
return rpcTransportSocket.sendRequestSocket(rpcRequestModel);
}
/**客服端的动态代理,会调用上面的invoke方法*/
public <T> T clientProxy(final Class<T> interfaceClass){
return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),new Class[]{interfaceClass},new RemoteInvocationHandler(host, port));
}
}
服务端启动测试代码
package com.lh.spring.boot.zk.rpc;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 15:12
* @email: hao.liang.ext@siemens.com
**/
public class RpcServiceDemo {
public static void main(String[] args) {
RpcService rpcService = new RpcService();
rpcService.publisher(new HelloServiceImpl() , 8098);
}
}
客户端启动测试代码
package com.lh.spring.boot.zk.rpc;
/**
* @description:
* @author: lianghao
* @create: 2019-05-31 15:14
**/
public class RpcClientDemo {
public static void main(String[] args) {
RemoteInvocationHandler remoteInvocationHandler = new RemoteInvocationHandler("127.0.0.1",8098);
IHelloService helloService = remoteInvocationHandler.clientProxy(IHelloService.class);
System.out.println(helloService.sayHello("lianghao"));
}
}