分布式服务框架 如何设计一个更合理的协议
1、概述
前面我们聊了如何设计一款分布式服务框架的问题,并且编码实现了一个简单的分布式服务框架 cheese, 目前 cheese 基本具备分布式服务框架的基本功能。后面我们又引入了缓存机制,以及使用Socket替代了最开始的 RestTemplate。并且还学习了网络相关的知识点和HTTP协议。今天我们就继续分析,如何继续优化我们的Cheese,让她变得更加高效简洁。
2、HTTP协议合不合适
我们回忆一下之前学习的HTTP请求的组成,大概是这个样子,
如果展开请求头和响应头 内容会更多,如果是浏览器访问肯定是没问题,但是如果用在Cheese 里面是否合适呢。你想想,Jerry就是想问Tom 要一块奶酪,一个简单的请求,难道还要按照HTTP协议约定的格式拼接一大堆和奶酪无关的东西,然后组成一个HTTP请求发过去,这样不仅会影响Cheese的远程调用的效率更是一种资源浪费。想想一个HTTP请求从源端到目标端经历的那些是不是头皮发麻。 (参考这里)
这个问题就是HTTP协议里面存在很多和业务需求无关的信息,但是我们又不能去掉,否则解析的时候会出现问题。 那么怎么解决呢,显而易见解决方案就是放弃HTTP协议。
3、一个更为合理的协议
3.1、协议的概念
首先说明一下 这里我们说的协议是工作在应用层的,也就是类似HTTP协议的那种,传输层依然还是TCP协议。这里大家可以先 回忆一下之前的文章中反复提到的一句话 客户端和服务器可以通过 Socket
建立网络连接 然后使用Socket对象的输入输出流 进行数据交换 ,(传送门)
我们仔细想想,既然是数据交换,那么协议的本质就是定义一组固定格式的数据,客户端按照这种格式组装请求报文,服务端按照同样的方式解析请求报文。这里的 固定格式 就是协议的体现了
3.2、 设计一个合理的固定格式
在这之前我们还是先给我们的协议取个名字吧,姑且就叫 Cheese 协议吧。我们回忆一下之前的 RemoteServer 2.0 设计的思路。也就是回到 Tom & Jerry的那个案例中去
之前的步骤 大概是这样 (懒得打字了,截图吧)
这是一个抽象的过程,我们这里将上述步骤可以进一步细化,如下所示
我们这里设计的 Cheese 协议说的透彻点就是如何封装请求对象和响应对象。根据上图我们可以大概的知道这一组对象主要包括的属性,其中请求对象 至少需要5个属性,首先是服务对应的类名,客户端需要告诉服务端执行哪一个类,接着还有方法名以及参数类型和返回值类型等等。返回对象主要有返回值和返回状态标识,如果发生异常了还需要将异常信息返回给客户端。
设计完成后按照上图描述的 Jerry 和 Tom 的步骤 传递这一组对象就可以实现这个通信的过程了。
4、Cheese 协议的落地
4.1、请求对象和响应对象的设计
这部分内容主要涉及请求和响应对象,首先定义出一个顶层的接口,里面包含设置返回码和服务端ip
package org.wcan.cheese.protocol;import java.io.Serializable;/*** @Description* @Author wcan* @Date 2025/1/16 下午 23:37* @Version 1.0*/
public interface CheeseProtocol extends Serializable {public void setResponseCode(Integer responseCode);public void setServerIp(String serverIp);
}
接着我们实现请求对象和响应对象的适配层,这里引入一个抽象类 AbstractCheeseProtocol
package org.wcan.cheese.protocol;/*** @Description* @Author wcan* @Date 2025/1/17 下午 17:12* @Version 1.0*/
public class AbstractCheeseProtocol implements CheeseProtocol{public Integer responseCode = 200;public String serverIp = null;public Integer getResponseCode() {return responseCode;}public String getServerIp() {return serverIp;}@Overridepublic void setResponseCode(Integer responseCode) {this.responseCode= responseCode;}@Overridepublic void setServerIp(String serverIp) {this.serverIp = serverIp;}
}
最后给出 CheeseRequest 和 CheeseResponse 的代码
package org.wcan.cheese.protocol;import java.util.Arrays;
import java.util.Objects;/*** @Description Cheese 请求对象* @Author wcan* @Date 2025/1/16 下午 23:15* @Version 1.0*/
public class CheeseRequest extends AbstractCheeseProtocol{public String className;public String methodName;private Class<?> returnValueType;private Class[] parameterTypes;private Object[] parameterValue;public CheeseRequest() {}public CheeseRequest(String className, String methodName, Class<?> returnValueType, Class[] parameterTypes, Object[] parameterValue) {this.className = className;this.methodName = methodName;this.returnValueType = returnValueType;this.parameterTypes = parameterTypes;this.parameterValue = parameterValue;}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 Class<?> getReturnValueType() {return returnValueType;}public void setReturnValueType(Class<?> returnValueType) {this.returnValueType = returnValueType;}public Class[] getParameterTypes() {return parameterTypes;}public void setParameterTypes(Class[] parameterTypes) {this.parameterTypes = parameterTypes;}public Object[] getParameterValue() {return parameterValue;}public void setParameterValue(Object[] parameterValue) {this.parameterValue = parameterValue;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;CheeseRequest that = (CheeseRequest) o;return Objects.equals(className, that.className) && Objects.equals(methodName, that.methodName) && Objects.equals(returnValueType, that.returnValueType) && Arrays.equals(parameterTypes, that.parameterTypes) && Arrays.equals(parameterValue, that.parameterValue);}@Overridepublic int hashCode() {int result = Objects.hash(className, methodName, returnValueType);result = 31 * result + Arrays.hashCode(parameterTypes);result = 31 * result + Arrays.hashCode(parameterValue);return result;}@Overridepublic String toString() {return "CheeseRequest{" +"className='" + className + '\'' +", methodName='" + methodName + '\'' +", returnValueType=" + returnValueType +", parameterTypes=" + Arrays.toString(parameterTypes) +", parameterValue=" + Arrays.toString(parameterValue) +'}';}
}
package org.wcan.cheese.protocol;/*** @Description Cheese 请求对象* @Author wcan* @Date 2025/1/16 下午 23:15* @Version 1.0*/
public class CheeseResponse extends AbstractCheeseProtocol {private Object returnValue;private Exception exceptionValue;public CheeseResponse() {}public CheeseResponse(Object returnValue, Exception exceptionValue) {this.returnValue = returnValue;this.exceptionValue = exceptionValue;}public Object getReturnValue() {return returnValue;}public void setReturnValue(Object returnValue) {this.returnValue = returnValue;}public Exception getExceptionValue() {return exceptionValue;}public void setExceptionValue(Exception exceptionValue) {this.exceptionValue = exceptionValue;}@Overridepublic String toString() {return "CheeseResponse{" +"returnValue=" + returnValue +", exceptionValue=" + exceptionValue +'}';}
}
4.2、服务端组件设计
服务端的逻辑相对简单一些 ,主要就是解析CheeseRequest对象,获取类名、方法名、返回值类型以及入参类型这几个关键的信息,然后通过反射调用对应的目标方法,最后将结果封装成CheeseResponse对象返回给客户端。
首先我们使用 NIO 实现 ServerEndpoint
package org.wcan.cheese.remote.cheese;import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.wcan.cheese.execute.ReflectionExecute;
import org.wcan.cheese.protocol.CheeseRequest;
import org.wcan.cheese.protocol.CheeseResponse;import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;/*** @Description rpc 通信端点* @Author wcan* @Date 2025/1/17 下午 14:15* @Version 1.0*/
@Component
public class ServerEndpoint {@Autowiredprivate ReflectionExecute reflectionExecute;@Value(value = "${cheesePort:8000}")private int cheesePort; // 监听端口public void ServerStart() {try {// 打开服务器端的 ServerSocketChannelServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.bind(new java.net.InetSocketAddress(cheesePort));serverSocketChannel.configureBlocking(false);// 打开 SelectorSelector selector = Selector.open();serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);System.out.println("服务器正在运行,监听端口 " + cheesePort);//TODO 注册端口while (true) {// 阻塞,等待 I/O 事件发生selector.select();// 获取所有发生的事件Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();while (selectedKeys.hasNext()) {SelectionKey key = selectedKeys.next();selectedKeys.remove();if (key.isAcceptable()) {// 接受连接请求handleAccept(serverSocketChannel, selector);} else if (key.isReadable()) {// 处理读取请求handleResponse(key);}}}} catch (IOException e) {e.printStackTrace();}}private static void handleAccept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {// 接受客户端连接SocketChannel socketChannel = serverSocketChannel.accept();socketChannel.configureBlocking(false);// 注册到 Selector,监听读事件socketChannel.register(selector, SelectionKey.OP_READ);System.out.println("新连接接入:" + socketChannel.getRemoteAddress());}private void handleResponse(SelectionKey key) throws IOException {SocketChannel socketChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);int bytesRead = socketChannel.read(buffer);if (bytesRead == -1) {socketChannel.close();System.out.println("连接关闭");return;}//获取请求内容String request = new String(buffer.array(), 0, bytesRead, StandardCharsets.UTF_8);ObjectMapper objectMapper = new ObjectMapper();CheeseRequest cheeseRequest = objectMapper.readValue(request, CheeseRequest.class);//执行请求CheeseResponse cheeseResponse = reflectionExecute.execute(cheeseRequest);//返回内容String response = objectMapper.writeValueAsString(cheeseResponse);ByteBuffer byteBuffer = ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8));// 发送响应数据while (byteBuffer.hasRemaining()) {socketChannel.write(byteBuffer);}socketChannel.close();System.out.println("响应已发送");}
}
接着 我们编写反射调用指定方法的工具类
package org.wcan.cheese.execute;import org.springframework.stereotype.Component;
import org.wcan.cheese.protocol.CheeseRequest;
import org.wcan.cheese.protocol.CheeseResponse;import java.lang.reflect.Method;
import java.util.Arrays;/*** @Description* @Author wcan* @Date 2025/1/16 下午 23:26* @Version 1.0*/
@Component
public class ReflectionExecute {public CheeseResponse execute(CheeseRequest cheeseRequest) {CheeseResponse cheeseResponse = new CheeseResponse();String className = cheeseRequest.getClassName();String methodName = cheeseRequest.getMethodName();
// Class<?> returnValueType = cheeseRequest.getReturnValueType();
// Class[] parameterTypes = cheeseRequest.getParameterTypes();try {Class<?> aClass = Class.forName(className);Method method = aClass.getMethod(methodName, cheeseRequest.getParameterTypes());Object invoke = method.invoke(aClass.newInstance(), cheeseRequest.getParameterValue());cheeseResponse.setReturnValue(invoke);} catch (Exception e) {cheeseResponse.setExceptionValue(e);}return cheeseResponse;}}
至此服务端的逻辑已经完成了
4.3、服务端功能测试
我们先测试一下编写的服务组件,在 tom-store 工程里 新建一个Service类 (工程代码从这里下载)
package org.tom.service;import org.springframework.stereotype.Service;import java.util.HashMap;
import java.util.Map;/*** @Description* @Author wcan* @Date 2025/1/20 下午 14:26* @Version 1.0*/
@Service
public class CheeseService {public Map<String, Object> getCheese() throws Exception{Map<String, Object> map = new HashMap<String, Object>();map.put("cheese", "A piece of cheese on the small table in the room");map.put("msg","我正在约会 不要打扰我");return map;}public Map<String, Object> getCheeseByName(String name,Integer size) throws Exception{Map<String, Object> map = new HashMap<String, Object>();map.put("cheese", "A "+ size+ "-centimeter piece of cheese is on the table");map.put("msg","hi "+name +"! 我正在约会 不要打扰我");return map;}
}
接着我们编写一个测试类
public class TestDemo {public static void main(String[] args) {CheeseRequest cheeseRequest = new CheeseRequest();cheeseRequest.setClassName("org.tom.service.CheeseService");cheeseRequest.setMethodName("getCheeseByName");cheeseRequest.setReturnValueType(Map.class);cheeseRequest.setParameterTypes(new Class[]{String.class,Integer.class});cheeseRequest.setParameterValue(new Object[]{"乔峰",35});CheeseResponse cheeseResponse = new ReflectionExecute().execute(cheeseRequest);Object returnValue = cheeseResponse.getReturnValue();System.out.println(returnValue);}
}
执行后结果如下图所示:
至此服务端的反射调用的逻辑能走通,接着我们后续就能通过Socket 来发送 CheeseRequest 对象了。
4.4、客户端组件设计
客户端主要承载的能力是 连接服务端,将Jerry 需要调用Tom 的服务的元信息(类名、入参、入参类型、返回值类型)封装成 CheeseRequest 对象,然后通过Socket 发送到服务端。
package org.wcan.cheese.remote.cheese;import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.wcan.cheese.protocol.CheeseRequest;
import org.wcan.cheese.protocol.CheeseResponse;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;/*** @Description* @Author wcan* @Date 2025/1/17 下午 15:13* @Version 1.0*/
@Component
public class ClientEndpoint {@Value(value = "${cheesePort:8000}")private int cheesePort; // 监听端口public CheeseResponse doRequest(CheeseRequest cheeseRequest){SocketChannel client = null;CheeseResponse cheeseResponse = null;try {// 创建一个客户端SocketChannel,并连接到服务端client = SocketChannel.open(new InetSocketAddress(cheeseRequest.getServerIp(), 8000));// 设置为非阻塞模式client.configureBlocking(false);ObjectMapper objectMapper = new ObjectMapper();// 准备发送的数据String request = objectMapper.writeValueAsString(cheeseRequest);// 使用Charset将字符串编码成字节ByteBuffer buffer = Charset.forName("UTF-8").encode(request);// 发送数据到服务端while (buffer.hasRemaining()) {client.write(buffer);}System.out.println("Message sent to the server: " + request);// 等待服务端响应并读取响应数据// 创建一个缓冲区用于接收服务端的响应ByteBuffer readBuffer = ByteBuffer.allocate(1024);int bytesRead = 0;// 不断尝试读取服务端响应while (bytesRead == 0) {bytesRead = client.read(readBuffer);}// 读取数据完成,解码并输出响应消息if (bytesRead > 0) {readBuffer.flip();String response = Charset.forName("UTF-8").decode(readBuffer).toString();cheeseResponse = objectMapper.readValue(response, CheeseResponse.class);System.out.println("Response from server: " + cheeseResponse);}} catch (IOException e) {throw new RuntimeException(e);} finally {try {if (client != null && client.isOpen()) {client.close();}} catch (IOException e) {e.printStackTrace();}}return cheeseResponse;}
}
我们编写好了 ClientEndpoint,客户端的核心内容还有一部分,那就是我们需要和服务发现组件集成。
4.5、CheeseRemoteExecute 实现
这里我们设计一个 CheeseRemoteExecute 组件,通过这个组件将 ClientEndpoint 组件和DiscoveryServer组件关联起来,DiscoveryServer组件从注册中心获取服务端的ip和端口号信息 然后交给ClientEndpoint处理。
package org.wcan.cheese.execute;import org.springframework.stereotype.Service;
import org.wcan.cheese.DiscoveryServer;
import org.wcan.cheese.RemoteExecute;
import org.wcan.cheese.protocol.CheeseRequest;
import org.wcan.cheese.protocol.CheeseResponse;
import org.wcan.cheese.remote.cheese.ClientEndpoint;import java.util.HashMap;
import java.util.Map;/*** @Description* @Author wcan* @Date 2024/10/27 下午 19:24* @ClassName HttpRemoteExecute* @Version 1.0*/
@Service
public class CheeseRemoteExecute implements RemoteExecute {private DiscoveryServer discoveryServer;private ClientEndpoint clientEndpoint;public CheeseRemoteExecute(DiscoveryServer discoveryServer,ClientEndpoint clientEndpoint) {this.discoveryServer = discoveryServer;this.clientEndpoint = clientEndpoint;}@Overridepublic String execute(String serviceName) throws Exception {return null;}@Overridepublic Map<String, Object> execute(String serviceName, Object[] params) throws Exception {String[] serviceNames = serviceName.split("#");String className = serviceNames[0];String methodName = serviceNames[1];String serverUrl = discoveryServer.getSingleServer(className);String[] split = serverUrl.split(":");String serverIp = split[0];CheeseRequest cheeseRequest = new CheeseRequest();cheeseRequest.setClassName(className);cheeseRequest.setMethodName(methodName);cheeseRequest.setReturnValueType(Map.class);Class[] classes = null;if(params.length>0){classes = new Class[params.length];for (int i = 0; i <params.length; i++) {classes[i] = params[i].getClass();}}cheeseRequest.setParameterTypes(classes);cheeseRequest.setParameterValue(params);cheeseRequest.setServerIp(serverIp);CheeseResponse cheeseResponse = clientEndpoint.doRequest(cheeseRequest);Object returnValue = cheeseResponse.getReturnValue();HashMap<String, Object> objectHashMap = new HashMap<>();objectHashMap.put("data", returnValue);return objectHashMap;}
}
到这里我们的 Cheese 协议已经开发完成了,后面我们需要做的就是把它集成到框架里进行工程化落地。
5、工程化落地
5.1、ServerEndpoint 集成方案
当我们将 tom-store 服务启动起来后,ServerEndpoint 怎么启动呢,毫无疑问我们首先想到的就是 Spring容器启动的时候就初始化 ServerEndpoint 组件,然后随着SpringBoot内置的Tomcat启动而启动,这个时候 tom-store 服务大概就是这个样子
9000端口负责处理HTTP请求,8000端口处理我们自己设计的 Cheese 协议请求。同样的我们启动Jerry 服务也是上图中描述的样子,无论是 Tom 还是Jerry 他们既可以是服务端也可以是客户端。
集成方案如下,我们改造一下 ServerLister 组件,将 ServerEndpoint 组件注入进去,并且在ServerLister 的构造器中使用一个线程异步启动 ServerEndpoint 组件。相关代码如下
package org.wcan.cheese.event;import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.wcan.cheese.config.CheeseConfig;
import org.wcan.cheese.remote.cheese.ServerEndpoint;import java.util.HashMap;
import java.util.Map;@Component
public class ServerLister implements ApplicationListener<ApplicationReadyEvent> {private final RegisterEvent registerEvent;private final CheeseConfig cheeseConfig;private final ServerEndpoint serverEndpoint;public ServerLister(RegisterEvent registerEvent, CheeseConfig cheeseConfig, ServerEndpoint serverEndpoint) {this.registerEvent = registerEvent;this.cheeseConfig = cheeseConfig;this.serverEndpoint = serverEndpoint;new Thread(() -> serverEndpoint.ServerStart()).start();}@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {System.out.println("所有的 Controller 和它们的请求映射:");Map<String, Object> serverMap = new HashMap<String, Object>();Map<String, Object> controllers = event.getApplicationContext().getBeansWithAnnotation(Controller.class);String serverPackage = cheeseConfig.getServerPackage();if (null == serverPackage || "".equals(serverPackage))return;controllers.forEach((key, value) -> {if (value.toString().contains(serverPackage)) {serverMap.put(key.toString(), value.getClass().getName());}});Map<String, Object> servers = event.getApplicationContext().getBeansWithAnnotation(Service.class);servers.forEach((key, value) -> {if (value.toString().contains(serverPackage)) {serverMap.put(key.toString(), value.getClass().getName());}});registerEvent.registerServer(serverMap);}}
5.2、集成测试
PS: 大家可以去仓库拉取完整的工程化代码运行
我们分别启动 tom-store 和 jerry-store 两个工程 ,然后浏览器访问
http://localhost:8001/getCheeseByName?name=jerry&size=5
我们就能看到效果了
我们观察控制台,也能看到调用的的时候打印的信息
5.3、如何处理 ServerEndpoint 的启停
相信聪明的你肯定 能想到单独开一个线程启动 ServerEndpoint 组件的好处,第一是异步启动不会影响到主服务的启动效率,第二是子线程如果发生了异常不会影响到主线程的运行。这就是偷偷new 一个线程去处理 ServerEndpoint 的好处
但是这么做也有一个问题或许要考虑,假设子线程发生了异常终止,在不重启服务的情况下 怎么把 ServerEndpoint 重新拉起来呢。或者我想要不停服的情况下单独停止 ServerEndpoint,假设ServerEndpoint 遭受了恶意攻击,影响了主服务业务我们要单独停掉 ServerEndpoint 。这种情况需要怎么处理呢
我们改造一下ServerEndpoint 类 ,加入两个方法,改造后的代码如下
@Component
public class ServerEndpoint {@Autowiredprivate ReflectionExecute reflectionExecute;private ServerSocketChannel serverSocketChannel;private Selector selector;@Value(value = "${cheesePort:8000}")private int cheesePort = 8000; // 监听端口public void ServerStart() {try {// 打开服务器端的 ServerSocketChannelserverSocketChannel = ServerSocketChannel.open();serverSocketChannel.bind(new java.net.InetSocketAddress(cheesePort));serverSocketChannel.configureBlocking(false);// 打开 Selectorselector = Selector.open();serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);System.out.println("服务器正在运行,监听端口 " + cheesePort);//TODO 注册端口while (true) {// 阻塞,等待 I/O 事件发生selector.select();// 获取所有发生的事件Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();while (selectedKeys.hasNext()) {SelectionKey key = selectedKeys.next();selectedKeys.remove();if (key.isAcceptable()) {// 接受连接请求handleAccept(serverSocketChannel, selector);} else if (key.isReadable()) {// 处理读取请求handleResponse(key);}}}} catch (IOException e) {e.printStackTrace();}}public void stopServer() throws IOException {this.serverSocketChannel.close();this.selector.close();System.out.println("服务器已关闭");}public void restartServer() throws IOException {stopServer();new Thread(() -> ServerStart()).start();System.out.println("服务器正在重启");}private static void handleAccept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {// 接受客户端连接SocketChannel socketChannel = serverSocketChannel.accept();socketChannel.configureBlocking(false);// 注册到 Selector,监听读事件socketChannel.register(selector, SelectionKey.OP_READ);System.out.println("新连接接入:" + socketChannel.getRemoteAddress());}private void handleResponse(SelectionKey key) throws IOException {SocketChannel socketChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);int bytesRead = socketChannel.read(buffer);if (bytesRead == -1) {socketChannel.close();System.out.println("连接关闭");return;}//获取请求内容String request = new String(buffer.array(), 0, bytesRead, StandardCharsets.UTF_8);ObjectMapper objectMapper = new ObjectMapper();CheeseRequest cheeseRequest = objectMapper.readValue(request, CheeseRequest.class);//执行请求CheeseResponse cheeseResponse = reflectionExecute.execute(cheeseRequest);//返回内容String response = objectMapper.writeValueAsString(cheeseResponse);ByteBuffer byteBuffer = ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8));// 发送响应数据while (byteBuffer.hasRemaining()) {socketChannel.write(byteBuffer);}socketChannel.close();System.out.println("响应已发送");}
}
我们继续在 tom-store工程里加入一个Controller
@RestController
public class AdminController {@Autowiredprivate ServerEndpoint serverEndpoint;@RequestMapping("/stop")public String stopServer() throws IOException {serverEndpoint.stopServer();return "stop success";}@RequestMapping("/restart")public String restartServer() throws IOException {serverEndpoint.restartServer();return "restart success";}}
我们重启 tom-store 然后访问下面的地址
重启: http://localhost:9000/restart
停止: http://localhost:9000/stop
这是一个比较简单的方案,把 ServerEndpoint的存活权交给用户处理。
6、总结与思考
6.1、总结
这篇文章给大家介绍了如何自定义应用层的协议,根据我们的实际业务设计一个更合理的协议。我们主要的实现方案就是 基于 NIO 创建 Socket 通道传输根据Cheese协议封装的对象来完成客户端和服务端的数据交换。
6.2、关于Cheese的思考
数据从内存里传递到网络中这个过程会涉及到序列化,本篇文章我们使用的是 JSON序列化,这种方式比较直观,因为人可以看懂所以也方便调试。缺点就是效率不高,我们后面会研究一下常用的序列化方式,为我们的Cheese 协议 选择一种最佳的方案
在服务端我们使用的是反射执行目标方法,其实这是一个很耗时的操作,因为每次我们都要加载类的元信息,而类信息又是固定的,所以这里其实是可以优化的。
目前我们是把服务接口配在了配置文件中,比如 jerry-store 项目的配置文件中serviceName 就是指定调用的服务接口,程序拿着这个接口去注册中心获取这个接口的注册信息
spring.application.name=jerry-store
server.port=8001zkUrl=XXXX
zookeeperBasePath=/jerry
nodePath=/config
timeout=5000
#serverPackage=org.jerry##配置接口编号
serviceName=org.tom.service.CheeseService#getCheeseByName##cheese协议端口
cheesePort=8002
这种方法实现比较简单,但是你肯定看的出来这并不是一个好的解决方案,我们应该思考将serviceName放在哪里合适。
后面我们讨论的话题将主要围绕这三点展开,让我们的 Cheese 更加健壮。
相关文章:

分布式服务框架 如何设计一个更合理的协议
1、概述 前面我们聊了如何设计一款分布式服务框架的问题,并且编码实现了一个简单的分布式服务框架 cheese, 目前 cheese 基本具备分布式服务框架的基本功能。后面我们又引入了缓存机制,以及使用Socket替代了最开始的 RestTemplate。并且还学习了网络相关…...

Unity使用iTextSharp导出PDF-02基础结构及设置中文字体
基础结构 1.创建一个Document对象 2.使用PdfWriter创建PDF文档 3.打开文档 4.添加内容,调用文档Add方法添加内容时,内容写入到输出流中 5.关闭文档 using UnityEngine; using iTextSharp.text; using System.IO; using iTextSharp.text.pdf; using Sys…...

Kafka因文件句柄数过多导致挂掉的排查与解决
一、问题现象 在k8s集群中部署了多个服务,包括Kafka、TDengine集群和Java等。这些服务使用NFS作为持久化存储方案。最近遇到了一个问题:Kafka频繁报错并最终挂掉。错误日志如下: 2025-02-09T09:39:07,022] INF0 [LogLoader partition__cons…...

【LeetCode Hot100 多维动态规划】最小路径和、最长回文子串、最长公共子序列、编辑距离
多维动态规划 机器人路径问题思路代码实现 最小路径和问题动态规划思路状态转移方程边界条件 代码实现 最长回文子串思路代码实现 最长公共子序列(LCS)题目描述解决方案 —— 动态规划1. 状态定义2. 状态转移方程3. 初始化4. 代码实现 编辑距离ÿ…...

PRC框架-Dubbo
RPC框架 RPC(Remote Procedure Call,远程过程调用)框架是一种允许客户端通过网络调用服务器端程序的技术。以下是常见的RPC框架及其特点: 1. 基于HTTP/REST的RPC框架 特点:简单易用,与Web开发无缝集成&am…...

智能检测摄像头模块在客流统计中的应用
工作原理 基于视频分析技术:智能检测摄像头模块通过捕捉监控区域内的视频画面,运用图像识别算法对视频中的人体进行检测、跟踪和分析。可以识别出人体的轮廓、姿态等特征,进而区分不同的个体,实现对客流的统计。 基于红外感应技…...

[LLM面试题] 指示微调(Prompt-tuning)与 Prefix-tuning区别
一、提示调整(Prompt Tuning) Prompt Tuning是一种通过改变输入提示语(input prompt)以获得更优模型效果的技术。举个例子,如果我们想将一条英语句子翻译成德语,可以采用多种不同的方式向模型提问,如下图所示…...

【CubeMX+STM32】SD卡 U盘文件系统 USB+FATFS
本篇,将使用CubeMXKeil, 创建一个 USBTF卡存储FatFS 的虚拟U盘读写工程。 目录 一、简述 二、CubeMX 配置 SDIO DMA FatFs USB 三、Keil 编辑代码 四、实验效果 串口助手,实现效果: U盘,识别效果: 一、简述 上…...

在JVM的栈(虚拟机栈)中,除了栈帧(Stack Frame)还有什么?
在JVM的栈(虚拟机栈)中,除了栈帧(Stack Frame),还有其他一些与方法调用相关的重要信息。栈的主要作用是存储方法调用的执行过程中的上下文信息,栈帧是其中最关键的组成部分。 栈的组成 栈帧&am…...

# 解析Excel文件:处理Excel xlsx file not supported错误 [特殊字符]
解析Excel文件:处理Excel xlsx file not supported错误 🧩 嘿,数据分析的小伙伴们!👋 我知道在处理Excel文件的时候,很多人可能会遇到这样一个错误:Excel xlsx file not supported。别担心&…...

图片下载不下来?即便点了另存为也无法下载?两种方法教你百分之百下载下来
前言,我要讲的是网站没有禁鼠标右键,可以右键,也可以打开控制台,图片也不用付费这种。 一、用鼠标按住图片直接往桌面拖动,也可以打开开发者工具,在里面往外拖。 二、这个方法很有意思,在电脑的…...

Unity项目实战-Player玩家控制脚本实现
玩家控制脚本设计思路 1. 代码演变过程 1.1 初始阶段:单一Player类实现 最初的设计可能是一个包含所有功能的Player类: public class Player : MonoBehaviour {private CharacterController controller;private Animator animator;[SerializeField] …...

CP AUTOSAR标准之ICUDriver(AUTOSAR_SWS_ICUDriver)(更新中……)
1 简介和功能概述 该规范指定了AUTOSAR基础软件模块ICU驱动程序的功能、API和配置。 ICU驱动程序是一个使用输入捕获单元(ICU)来解调PWM信号、计数脉冲、测量频率和占空比、生成简单中断和唤醒中断的模块。 ICU驱动程序提供服务 信号边缘通知控制唤醒中断周期信号时间测…...

Python3 ImportError: cannot import name ‘XXX‘ from ‘XXX‘
个人博客地址:Python3 ImportError: cannot import name XXX from XXX | 一张假钞的真实世界 例如如下错误: $ python3 git.py Traceback (most recent call last):File "git.py", line 1, in <module>from git import RepoFile &quo…...

[学习笔记] Kotlin Compose-Multiplatform
Compose-Multiplatform 原文:https://github.com/zimoyin/StudyNotes-master/blob/master/compose-multiplatform/compose.md Compose Multiplatform 是 JetBrains 为桌面平台(macOS,Linux,Windows)和Web编写Kotlin UI…...

【R语言】t检验
t检验(t-test)是用于比较两个样本均值是否存在显著差异的一种统计方法。 t.test()函数的调用格式: t.test(x, yNULL, alternativec("two.sided", "less", "greater"), mu0, pairedFALSE, var.equalFALSE, co…...

flutter ListView Item复用源码解析
Flutter 的 ListView 的 Item 复用机制是其高性能列表渲染的核心,底层实现依赖于 Flutter 的渲染管线、Element 树和 Widget 树的协调机制。以下是 ListView 复用机制的源码级解析,结合关键类和核心逻辑进行分析。 1. ListView 的底层结构 ListView 的复…...

Spring Boot 配置 Mybatis 读写分离
JPA 的读写分离配置不能应用在 Mybatis 上, 所以 Mybatis 要单独处理 为了不影响原有代码, 使用了增加拦截器的方式, 在拦截器里根据 SQL 的 CRUD 来路由到不同的数据源 需要单独增加Mybatis的配置 Beanpublic SqlSessionFactory sqlSessionFactory(DataSource dataSource) t…...

网络初识-
网络的相关概念 一、局域网和广域网 将各种计算机、外部设备等相互连接起来,实现在这个范围内数据通信和资源共享的计算机网络。它的覆盖范围通常在几百米到几公里之内。例如,一个小型企业的办公室,通过交换机将多台电脑连接在一起…...

DNS污染:网络世界的“隐形劫持”与防御
在互联网的底层架构中,DNS(域名系统)如同数字世界的“导航员”,将用户输入的域名翻译成机器可读的IP地址。然而,DNS污染(DNS Poisoning)正像一场无声的“地址篡改”危机,威胁着全球网…...

MQTT(Message Queuing Telemetry Transport)协议(三)
主题是什么 2. TCP 协议封装 tcp.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h>// 建立 TCP 连接 int tcp_connect(const char *server_ip, int s…...

多核cpu与时间片多线程的问题
在多核处理器中,每个核心可以独立运行一个线程。操作系统负责管理和调度这些线程,以确保高效利用处理器资源。下面详细解释如何获取时间片以及四个线程如何在四个核心上同时工作。 ### 时间片和调度 #### 1. 时间片(Time Slice)…...

电脑出现蓝屏英文怎么办?查看修复过程
电脑出现蓝屏英文是一种常见的电脑故障,它通常表示电脑遇到了严重的错误,需要停止运行以防止进一步的损坏。电脑蓝屏英文的原因可能有很多,比如硬件故障、驱动程序错误、系统文件损坏、病毒感染等。那么,当电脑出现蓝屏英文时&…...

安卓基础(第一集)
SharedPreferences(本地存储简单数据) 在 Android 中,SharedPreferences 用于存储小型数据。 (1)存储数据 // 获取 SharedPreferences 对象 SharedPreferences sharedPreferences getSharedPreferences("MyPre…...

【从零开始入门unity游戏开发之——C#篇56】C#补充知识点——模式匹配
考虑到每个人基础可能不一样,且并不是所有人都有同时做2D、3D开发的需求,所以我把 【零基础入门unity游戏开发】 分为成了C#篇、unity通用篇、unity3D篇、unity2D篇。 【C#篇】:主要讲解C#的基础语法,包括变量、数据类型、运算符、流程控制、面向对象等,适合没有编程基础的…...

【数据可视化-16】珍爱网上海注册者情况分析
🧑 博主简介:曾任某智慧城市类企业算法总监,目前在美国市场的物流公司从事高级算法工程师一职,深耕人工智能领域,精通python数据挖掘、可视化、机器学习等,发表过AI相关的专利并多次在AI类比赛中获奖。CSDN…...

c/c++蓝桥杯经典编程题100道(21)背包问题
背包问题 ->返回c/c蓝桥杯经典编程题100道-目录 目录 背包问题 一、题型解释 二、例题问题描述 三、C语言实现 解法1:0-1背包(基础动态规划,难度★) 解法2:0-1背包(空间优化版,难度★…...

电赛DEEPSEEK
以下是针对竞赛题目的深度优化方案,重点解决频率接近时的滤波难题和相位测量精度问题: 以下是使用NI Multisim 14.3实现本项目的详细解决方案: 一、基础要求实现方案(模块化设计) 1. 双频信号发生电路 电路结构&…...

VSOMEIP ROUTING应用和CLIENT应用之间交互的消息
#define VSOMEIP_ASSIGN_CLIENT 0x00 // client应用请求分配client_id #define VSOMEIP_ASSIGN_CLIENT_ACK 0x01 // routing应用返回分配的client_id #define VSOMEIP_REGISTER_APPLICATION 0x02 // client应用注册someip应用 #…...

HTML之基本布局div|span
HTML基本布局使用 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"width<device-width>, initial-scale1.0"><title>布局</title> <…...