设计思路:
1. 自定义web服务:通过请求客户端发送http协议来实现
2. 请求处理器:根据传参的不同来做不同的处理,要不然需要写很多的接口
3. 本地服务注册器:记录服务和对应类的映射关系,例如orderService对应order方法
4. 代理类:消费者通过代理类去消费实例,无需关心内部实现
web服务器
采用vert.x框架实现,此类实现有很多种方式,例如vert.x,netty等
public class VertxHttpServer implements HttpServer{
@Override
public void doStart(int port) {
// 创建实例
Vertx vertx = Vertx.vertx();
// 创建HTTP服务器
io.vertx.core.http.HttpServer httpServer = vertx.createHttpServer();
// 监听端口并处理请求
httpServer.requestHandler(new HttpServerHandler());
//启动HTTP服务器并监听指定端口
httpServer.listen(port, result -> {
if (result.succeeded()) {
System.out.println("Server is now listening on port "+ port);
} else {
System.err.println("Failed to start server: " + result.cause());
}
});
}
}
本地服务注册器
利用map存储对应关系,key存储服务名称,value存储具体实现
public class LocalRegistry {
/**
* 注册消息存储,key 为服务名称、value 为服务的实现类
*/
private static final Map<String,Class<?>> map = new ConcurrentHashMap<>();
/**
* 注册服务
* @param serviceName
* @param clazz
*/
public static void registry(String serviceName, Class<?> clazz) {
map.put(serviceName, clazz);
}
/**
* 删除服务
* @param serviceName
*/
public static void remove(String serviceName) {
map.remove(serviceName);
}
/**
* 获取服务
* @param serviceName
* @return
*/
public static Class<?> get(String serviceName) {
return map.get(serviceName);
}
}
序列化器
采用jdk自带的序列化方式,也有可替换方案,例如protobuf等
代理模式
此处使用动态代理+工厂模式实现
public class ServiceProxy implements InvocationHandler {
/**
* 调用代理
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Serializer serializer = new JdkSerializer();
//构造请求
RpcRequest rpcRequest = RpcRequest.builder()
.serviceName(method.getDeclaringClass().getName())
.methodName(method.getName())
.parameterTypes(method.getParameterTypes())
.args(args)
.build();
byte[] bodyBytes = serializer.serialize(rpcRequest);
try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
.body(bodyBytes)
.execute()){
byte[] result = httpResponse.bodyBytes();
// 反序列化
RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
return rpcResponse.getData();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}