赞
踩
Sentinel开发了一个控制台给我们可以动态的去操作规则,方便了我们在项目运行过程中临时需要操作的一些情况,使用文档可以参考里面的第5点
1. 下载对应的jar包或者从源码级别编译sentinel-dashboard模块都可以
2. 启动即可,就是一个spring-boot项目
3. 控制台启动可以配置的一些参数
1. 引入以下模块即可
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.4</version>
</dependency>2.添加客户端启动参数
-Dcsp.sentinel.dashboard.server=127.0.0.1:7001 -Dproject.name=zxc
sp.sentinel.dashboard.server 为控制台地址
project.name 为客户端项目名称
以上参数都可以在 Sentinel控制台配置参数 找到
我本地的客户端程序还是比较简单,因为只是要进行测试,如下图
配置的参数,其中127.0.0.1:7001是我控制台的地址
以这种方式启动以后在控制台就可以看到如下,前提是引入了对应的依赖,上来说了,引入那个依赖sentinel就会把你当前的客户端注册到你指定的控制台上面去
总结:使用控制台还是比较简单的
1. 下载对应的jar包
2. 启动jar包,就是一个spring-boot项目的jar包
3. 引入对应的maven依赖
4. 添加对应的参数
5. 在控制台进行操作
控制台操作,直接点击簇点链路的流控等就会看到对应的操作页面,如流控规则
其他规则可以参考官网文档,这里就不细说了,后面有讲到这些规则的时候再进行细说
使用其实还是比较简单的,只要根据对应的文档进行下载,操作即可,不过你会不会好奇引入一个maven依赖,然后配置下参数,它就自动会帮我们注册到Sentinel上,这个是怎么做的,这个点会不会有点好奇呢?下面就来说下这个,看它是怎么做的
注:以下只说明是怎么做的逻辑,具体的实现可能不会说太多太细
需要下载源码才可以,下载过程在第一篇就说了,这里就不重复说了,可以参考
- Sentinel-core 模块下有个类叫 com.alibaba.csp.sentinel.Env
-
-
-
- public class Env {
-
- public static final Sph sph = new CtSph();
-
- static {
- // If init fails, the process will exit.
- //执行初始化逻辑,失败的话程序会直接退出
- InitExecutor.doInit();
- }
-
- }
-
-
- 具体的逻辑在这个doInit()方法里面
-
- public static void doInit() {
- //只执行一遍,使用原子量控制并发问题
- if (!initialized.compareAndSet(false, true)) {
- return;
- }
- try {
- //这里使用了SPI机制去加载InitFunc接口的实现类
- List<InitFunc> initFuncs = SpiLoader.of(InitFunc.class).loadInstanceListSorted();
- //进行排序处理,InitFunc可以通过标记@InitOrder注解来指定先后顺序
- List<OrderWrapper> initList = new ArrayList<OrderWrapper>();
- for (InitFunc initFunc : initFuncs) {
- RecordLog.info("[InitExecutor] Found init func: {}", initFunc.getClass().getCanonicalName());
- insertSorted(initList, initFunc);
- }
- //循环调用InitFunc方法的init()方法
- for (OrderWrapper w : initList) {
- w.func.init();
- RecordLog.info("[InitExecutor] Executing {} with order {}",
- w.func.getClass().getCanonicalName(), w.order);
- }
- } catch (Exception ex) {
- RecordLog.warn("[InitExecutor] WARN: Initialization failed", ex);
- ex.printStackTrace();
- } catch (Error error) {
- RecordLog.warn("[InitExecutor] ERROR: Initialization failed with fatal error", error);
- error.printStackTrace();
- }
- }
这里面使用了SPI机制加载InitFunc的接口这个是在最重要的一个点,SPI机制前面已经说了,不清楚的可以看下第二篇,因为这里加载了SPI,再看看我们依赖的那个模块下面有什么东西,以下是结构图
那么由于spi机制的存在,上面两个实现类在应用启动的时候就会被调用对应的init方法,我们来看下这两个实现类做了啥
- @Override
- public void init() throws Exception {
- //获取CommandCenter对象
- CommandCenter commandCenter = CommandCenterProvider.getCommandCenter();
-
- //为空则不进行任何处理
- if (commandCenter == null) {
- RecordLog.warn("[CommandCenterInitFunc] Cannot resolve CommandCenter");
- return;
- }
-
- //调用CommandCenter对象两个方法
- commandCenter.beforeStart();
- commandCenter.start();
- RecordLog.info("[CommandCenterInit] Starting command center: "
- + commandCenter.getClass().getCanonicalName());
- }
-
-
- 代码量很简单,接着我们就需要看下CommandCenterProvider这个提供者做了啥了
-
-
-
-
- public final class CommandCenterProvider {
-
- private static CommandCenter commandCenter = null;
-
- static {
- //解析实例
- resolveInstance();
- }
-
- private static void resolveInstance() {
- //又是利用spi机制获取CommandCenter然后取优先值最高的对象
- CommandCenter resolveCommandCenter = SpiLoader.of(CommandCenter.class).loadHighestPriorityInstance();
-
- if (resolveCommandCenter == null) {
- RecordLog.warn("[CommandCenterProvider] WARN: No existing CommandCenter found");
- } else {
- commandCenter = resolveCommandCenter;
- RecordLog.info("[CommandCenterProvider] CommandCenter resolved: {}", resolveCommandCenter.getClass()
- .getCanonicalName());
- }
- }
-
- /**
- * Get resolved {@link CommandCenter} instance.
- *
- * @return resolved {@code CommandCenter} instance
- */
- public static CommandCenter getCommandCenter() {
- return commandCenter;
- }
-
- private CommandCenterProvider() {}
- }
-
-
-
- 可以看到CommandCenterProvider一开始就去加载了,再次使用到spi机制,CommandCenter 有几个实现类,其中一个就是sentinel-transport-simple-http maven依赖里面提供的SimpleHttpCommandCenter实现类
通过上面的分析我们找到了SimpleHttpCommandCenter,那么接下来就是看这个类里面的beforeStart()和start()方法了
- com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter#beforeStart
-
-
- @Override
- @SuppressWarnings("rawtypes")
- public void beforeStart() throws Exception {
- // Register handlers
- //通过spi机制获取所有CommandHandler对象
- Map<String, CommandHandler> handlers = CommandHandlerProvider.getInstance().namedHandlers();
- //注册命令
- registerCommands(handlers);
- //注:这里使用了命令设计模式
- }
-
-
-
- public void start() throws Exception {
-
- //获取当前运行环境的线程核心数
- int nThreads = Runtime.getRuntime().availableProcessors();
-
- //声明线程池
- this.bizExecutor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(10),
- new NamedThreadFactory("sentinel-command-center-service-executor", true),
- new RejectedExecutionHandler() {
- @Override
- public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
- CommandCenterLog.info("EventTask rejected");
- throw new RejectedExecutionException();
- }
- });
-
- Runnable serverInitTask = new Runnable() {
- int port;
-
- {
- try {
- port = Integer.parseInt(TransportConfig.getPort());
- } catch (Exception e) {
- port = DEFAULT_PORT;
- }
- }
-
- @Override
- public void run() {
- boolean success = false;
- //创建ServerSocket客户端,用来接收控制台放松的消息
- ServerSocket serverSocket = getServerSocketFromBasePort(port);
-
- if (serverSocket != null) {
- CommandCenterLog.info("[CommandCenter] Begin listening at port " + serverSocket.getLocalPort());
- socketReference = serverSocket;
- //往线程池提交任务,类型为ServerThread
- executor.submit(new ServerThread(serverSocket));
- success = true;
- port = serverSocket.getLocalPort();
- } else {
- CommandCenterLog.info("[CommandCenter] chooses port fail, http command center will not work");
- }
-
- if (!success) {
- port = PORT_UNINITIALIZED;
- }
-
- TransportConfig.setRuntimePort(port);
- //关闭线程池
- executor.shutdown();
- }
-
- };
-
- //启动上面定义的线程
- new Thread(serverInitTask).start();
- }
-
-
-
- ServerThread的代码如下
-
-
-
- class ServerThread extends Thread {
-
- private ServerSocket serverSocket;
-
- ServerThread(ServerSocket s) {
- this.serverSocket = s;
- setName("sentinel-courier-server-accept-thread");
- }
-
- @Override
- public void run() {
- //死循环
- while (true) {
- Socket socket = null;
- try {
- //接收控制台发来的消息
- socket = this.serverSocket.accept();
- setSocketSoTimeout(socket);
- //事件任务,默认情况下控制台会一直发送 metric 事件
- HttpEventTask eventTask = new HttpEventTask(socket);
- //提交
- bizExecutor.submit(eventTask);
- } catch (Exception e) {
- CommandCenterLog.info("Server error", e);
- if (socket != null) {
- try {
- socket.close();
- } catch (Exception e1) {
- CommandCenterLog.info("Error when closing an opened socket", e1);
- }
- }
- try {
- // In case of infinite log.
- //每10ms就接收一次
- Thread.sleep(10);
- } catch (InterruptedException e1) {
- // Indicates the task should stop.
- break;
- }
- }
- }
- }
- }
-
-
-
- 这里面最核心的是HttpEventTask事件,用来接收处理控制器发过来的事件,看一下它的run方法,比较长,不过主要的逻辑就那几句
-
-
-
- @Override
- public void run() {
-
- if (socket == null) {
- return;
- }
-
- PrintWriter printWriter = null;
- InputStream inputStream = null;
- try {
- //整理获取数据...这一块就不解析了
- long start = System.currentTimeMillis();
- inputStream = new BufferedInputStream(socket.getInputStream());
- OutputStream outputStream = socket.getOutputStream();
-
- printWriter = new PrintWriter(
- new OutputStreamWriter(outputStream, Charset.forName(SentinelConfig.charset())));
-
- String firstLine = readLine(inputStream);
- CommandCenterLog.info("[SimpleHttpCommandCenter] Socket income: " + firstLine
- + ", addr: " + socket.getInetAddress());
- CommandRequest request = processQueryString(firstLine);
-
- if (firstLine.length() > 4 && StringUtil.equalsIgnoreCase("POST", firstLine.substring(0, 4))) {
- // Deal with post method
- processPostRequest(inputStream, request);
- }
-
- // Validate the target command.
- // 从请求中获取要执行的命令
- String commandName = HttpCommandUtils.getTarget(request);
- if (StringUtil.isBlank(commandName)) {
- writeResponse(printWriter, StatusCode.BAD_REQUEST, INVALID_COMMAND_MESSAGE);
- return;
- }
-
- System.out.println("commandName = " + commandName);
-
- // Find the matching command handler.
- //再从前面加载的命令中获取对应的命令处理器
- CommandHandler<?> commandHandler = SimpleHttpCommandCenter.getHandler(commandName);
- if (commandHandler != null) {
- //处理命令并响应给控制台
- CommandResponse<?> response = commandHandler.handle(request);
- handleResponse(response, printWriter);
- } else {
- // No matching command handler.
- //没有找到匹配的,直接报错
- writeResponse(printWriter, StatusCode.BAD_REQUEST, "Unknown command `" + commandName + '`');
- }
-
- long cost = System.currentTimeMillis() - start;
- CommandCenterLog.info("[SimpleHttpCommandCenter] Deal a socket task: " + firstLine
- + ", address: " + socket.getInetAddress() + ", time cost: " + cost + " ms");
- } catch (RequestException e) {
- writeResponse(printWriter, e.getStatusCode(), e.getMessage());
- } catch (Throwable e) {
- CommandCenterLog.warn("[SimpleHttpCommandCenter] CommandCenter error", e);
- try {
- if (printWriter != null) {
- String errorMessage = SERVER_ERROR_MESSAGE;
- e.printStackTrace();
- if (!writtenHead) {
- writeResponse(printWriter, StatusCode.INTERNAL_SERVER_ERROR, errorMessage);
- } else {
- printWriter.println(errorMessage);
- }
- printWriter.flush();
- }
- } catch (Exception e1) {
- CommandCenterLog.warn("Failed to write error response", e1);
- }
- } finally {
- closeResource(inputStream);
- closeResource(printWriter);
- closeResource(socket);
- }
- }
-
-
-
-
- 这里面最核心的就是命令行设计模式设计的CommandHandler对象了,这个对象的实现类在前面已经通过spi机制进行加载了,可以稍微看下有哪些
-
-
- 在 sentinel-transport-common模块中的com.alibaba.csp.sentinel.command.CommandHandler文件
-
-
-
- com.alibaba.csp.sentinel.command.handler.BasicInfoCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchActiveRuleCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchClusterNodeByIdCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchClusterNodeHumanCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchJsonTreeCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchOriginCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchSimpleClusterNodeCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchSystemStatusCommandHandler
- com.alibaba.csp.sentinel.command.handler.FetchTreeCommandHandler
- com.alibaba.csp.sentinel.command.handler.ModifyRulesCommandHandler
- com.alibaba.csp.sentinel.command.handler.OnOffGetCommandHandler
- com.alibaba.csp.sentinel.command.handler.OnOffSetCommandHandler
- com.alibaba.csp.sentinel.command.handler.SendMetricCommandHandler
- com.alibaba.csp.sentinel.command.handler.VersionCommandHandler
- com.alibaba.csp.sentinel.command.handler.cluster.FetchClusterModeCommandHandler
- com.alibaba.csp.sentinel.command.handler.cluster.ModifyClusterModeCommandHandler
- com.alibaba.csp.sentinel.command.handler.ApiCommandHandler
-
-
- 有以上这些实现,我们可以稍微看下ModifyRulesCommandHandler这个类,这是最重要的一个
-
-
-
-
-
- @Override
- public CommandResponse<String> handle(CommandRequest request) {
- //前面还是在整理获取数据
- // XXX from 1.7.2, force to fail when fastjson is older than 1.2.12
- // We may need a better solution on this.
- if (VersionUtil.fromVersionString(JSON.VERSION) < FASTJSON_MINIMAL_VER) {
- // fastjson too old
- return CommandResponse.ofFailure(new RuntimeException("The \"fastjson-" + JSON.VERSION
- + "\" introduced in application is too old, you need fastjson-1.2.12 at least."));
- }
- String type = request.getParam("type");
- // rule data in get parameter
- String data = request.getParam("data");
- if (StringUtil.isNotEmpty(data)) {
- try {
- data = URLDecoder.decode(data, "utf-8");
- } catch (Exception e) {
- RecordLog.info("Decode rule data error", e);
- return CommandResponse.ofFailure(e, "decode rule data error");
- }
- }
-
- RecordLog.info("Receiving rule change (type: {}): {}", type, data);
-
- String result = "success";
-
- //流控规则
- if (FLOW_RULE_TYPE.equalsIgnoreCase(type)) {
- //解析数据已经更新数据
- List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
- FlowRuleManager.loadRules(flowRules);
- //持久化数据
- if (!writeToDataSource(getFlowDataSource(), flowRules)) {
- result = WRITE_DS_FAILURE_MSG;
- }
- return CommandResponse.ofSuccess(result);
- } else if (AUTHORITY_RULE_TYPE.equalsIgnoreCase(type)) { //黑白名单
- //解析数据已经更新数据
- List<AuthorityRule> rules = JSONArray.parseArray(data, AuthorityRule.class);
- AuthorityRuleManager.loadRules(rules);
- //持久化数据
- if (!writeToDataSource(getAuthorityDataSource(), rules)) {
- result = WRITE_DS_FAILURE_MSG;
- }
- return CommandResponse.ofSuccess(result);
- } else if (DEGRADE_RULE_TYPE.equalsIgnoreCase(type)) {
- //降级数据
- List<DegradeRule> rules = JSONArray.parseArray(data, DegradeRule.class);
- DegradeRuleManager.loadRules(rules);
- //持久化数据
- if (!writeToDataSource(getDegradeDataSource(), rules)) {
- result = WRITE_DS_FAILURE_MSG;
- }
- return CommandResponse.ofSuccess(result);
- } else if (SYSTEM_RULE_TYPE.equalsIgnoreCase(type)) {
- //系统规则
- List<SystemRule> rules = JSONArray.parseArray(data, SystemRule.class);
- SystemRuleManager.loadRules(rules);
- //持久化数据
- if (!writeToDataSource(getSystemSource(), rules)) {
- result = WRITE_DS_FAILURE_MSG;
- }
- return CommandResponse.ofSuccess(result);
- }
- return CommandResponse.ofFailure(new IllegalArgumentException("invalid type"));
- }
-
-
-
- writeToDataSource 写到数据源的逻辑原来也在这里,不过这个后面再看就行了
总结:以上就是 CommandCenterInitFunc以及SimpleHttpCommandCenter的原理,客户端接收服务端的流程和逻辑处理,下面再讲另一个东西
看名字就知道是用来处理心跳机制的,也就是客户端发送信息给控制台的,下面就来看下具体的情况
- 先看下 HeartbeatSenderProvider 这个类做了啥
-
- public final class HeartbeatSenderProvider {
-
- private static HeartbeatSender heartbeatSender = null;
-
- static {
- //解析实例
- resolveInstance();
- }
-
- private static void resolveInstance() {
- //又是利用spi机制获取优先级最高的
- //我们引入sentinel-transport-simple-http会加载一个SimpleHttpHeartbeatSender,所以这里拿到的就是SimpleHttpHeartbeatSender
- //除非有其他实现类
- HeartbeatSender resolved = SpiLoader.of(HeartbeatSender.class).loadHighestPriorityInstance();
- if (resolved == null) {
- RecordLog.warn("[HeartbeatSenderProvider] WARN: No existing HeartbeatSender found");
- } else {
- heartbeatSender = resolved;
- RecordLog.info("[HeartbeatSenderProvider] HeartbeatSender activated: {}", resolved.getClass()
- .getCanonicalName());
- }
- }
-
- /**
- * Get resolved {@link HeartbeatSender} instance.
- *
- * @return resolved {@code HeartbeatSender} instance
- */
- public static HeartbeatSender getHeartbeatSender() {
- return heartbeatSender;
- }
-
- private HeartbeatSenderProvider() {}
- }
-
-
- HeartbeatSenderProvider这个类就是生成一个HeartbeatSender 对象,而我们这里实际上就是SimpleHttpHeartbeatSender对象
-
-
- com.alibaba.csp.sentinel.transport.init.HeartbeatSenderInitFunc#init
-
- @Override
- public void init() {
- //获取HeartbeatSender对象
- HeartbeatSender sender = HeartbeatSenderProvider.getHeartbeatSender();
- if (sender == null) {
- RecordLog.warn("[HeartbeatSenderInitFunc] WARN: No HeartbeatSender loaded");
- return;
- }
-
- //如果需要初始话定时线程池
- initSchedulerIfNeeded();
- //获取发送间隔
- long interval = retrieveInterval(sender);
- //把间隔设置回去
- setIntervalIfNotExists(interval);
- //启动任务定时发送心跳
- scheduleHeartbeatTask(sender, interval);
- }
-
-
-
- retrieveInterval 这个方法里面就可以看到具体的间隔时间是怎么拿取的,可以通过
- csp.sentinel.heartbeat.interval.ms参数进行设置,原理也就是在这个位置
-
-
-
-
- long retrieveInterval(/*@NonNull*/ HeartbeatSender sender) {
- //从配置中获取,如果是有效的直接返回
- Long intervalInConfig = TransportConfig.getHeartbeatIntervalMs();
- if (isValidHeartbeatInterval(intervalInConfig)) {
- RecordLog.info("[HeartbeatSenderInitFunc] Using heartbeat interval "
- + "in Sentinel config property: " + intervalInConfig);
- return intervalInConfig;
- } else {
- //如果无效则从HeartbeatSender获取这个间隔, SimpleHttpHeartbeatSender默认为10s执行一次
- long senderInterval = sender.intervalMs();
- RecordLog.info("[HeartbeatSenderInit] Heartbeat interval not configured in "
- + "config property or invalid, using sender default: " + senderInterval);
- return senderInterval;
- }
- }
-
-
- 最后再看下 scheduleHeartbeatTask方法,具体发送心跳的逻辑
-
-
-
- private void scheduleHeartbeatTask(/*@NonNull*/ final HeartbeatSender sender, /*@Valid*/ long interval) {
- pool.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- try {
- //发送心跳
- sender.sendHeartbeat();
- } catch (Throwable e) {
- //失败了也只是当时那个失败,不会停止整个线程
- RecordLog.warn("[HeartbeatSender] Send heartbeat error", e);
- }
- }
- //5秒后启动,每interval执行一次
- }, 5000, interval, TimeUnit.MILLISECONDS);
- RecordLog.info("[HeartbeatSenderInit] HeartbeatSender started: "
- + sender.getClass().getCanonicalName());
- }
-
-
-
-
-
- 那么逻辑很明显就在具体的HeartbeatSender 进行实现了,下面再具体看一下
-
-
-
-
- com.alibaba.csp.sentinel.transport.heartbeat.SimpleHttpHeartbeatSender#sendHeartbeat
-
-
-
- @Override
- public boolean sendHeartbeat() throws Exception {
-
- //前置判断
- if (TransportConfig.getRuntimePort() <= 0) {
- RecordLog.info("[SimpleHttpHeartbeatSender] Command server port not initialized, won't send heartbeat");
- return false;
- }
- //获取控制台的地址,就是csp.sentinel.dashboard.server参数配置的,可以配置多个,多个时会进行负载均衡请求
- Endpoint addrInfo = getAvailableAddress();
- if (addrInfo == null) {
- return false;
- }
-
- //封装请求对象以及设置参数
- SimpleHttpRequest request = new SimpleHttpRequest(addrInfo, TransportConfig.getHeartbeatApiPath());
- request.setParams(heartBeat.generateCurrentMessage());
- try {
- //发送http请求
- SimpleHttpResponse response = httpClient.post(request);
- if (response.getStatusCode() == OK_STATUS) {
- return true;
- } else if (clientErrorCode(response.getStatusCode()) || serverErrorCode(response.getStatusCode())) {
- RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addrInfo
- + ", http status code: " + response.getStatusCode());
- }
- } catch (Exception e) {
- RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addrInfo, e);
- }
- return false;
- }
-
-
-
-
-
- 逻辑还是挺清晰的,这里唯一的问题就是请求地址是怎么确定的,可以再稍微看下
- SimpleHttpHeartbeatSender构造方法里面获取的,TransportConfig.getConsoleServerList()
- 这个就不进去看了,就是解析csp.sentinel.dashboard.server参数,多个以,分割,然后把它组成一个个
- Endpoint对象放到列表去
-
-
-
- public SimpleHttpHeartbeatSender() {
- // Retrieve the list of default addresses.
- //获取地址列表
- List<Endpoint> newAddrs = TransportConfig.getConsoleServerList();
- if (newAddrs.isEmpty()) {
- RecordLog.warn("[SimpleHttpHeartbeatSender] Dashboard server address not configured or not available");
- } else {
- RecordLog.info("[SimpleHttpHeartbeatSender] Default console address list retrieved: {}", newAddrs);
- }
- //赋值
- this.addressList = newAddrs;
- }
-
-
- 至此心跳逻辑就分析完了,发下心跳的时候自然是会往控制台注册自己的,至于控制台规则是怎么来的,那个逻辑就是控制台那边通过注册的ip,调用对应的借口获取然后展示到上面的,后面如果有时间,再写篇文章去看这个问题,其实原理都是一样的
明显心跳的逻辑比接收的逻辑要简单很多,这里依然使用的设计模式有策略模式以及spi机制
到这里,自动注册的原理就分析完了,再稍微总结一下原理
1, 引入sentinel-transport-simple-http的maven依赖
2. Env初始快调用InitFunc的init方法
3. 引入sentinel-transport-simple-http时会同时依赖sentinel-transport-common,而该模块会有InitFunc的实现,主要有以下两个
CommandCenterInitFunc:用于接收控制台发送消息给客户段的
HeartbeatSenderInitFunc:用于发送心跳给控制台的
4. 在执行上面这两个的时候会有对应的实现类,而这两个实现类是在sentinel-transport-simple-http模块中的,主要是
SimpleHttpCommandCenter:用于实现接收控制台发送消息给客户段
SimpleHttpHeartbeatSender:用于实现发送心跳也就是注册信息给控制台的
到此就结束了,在这个过程中可以看到作者是如何巧妙的使用spi机制进行解耦的,Env中执行调用了InitFunc的init方法,而sentinel-transport-simple-htt模块中自己根据spi机制定义了对应的规范,有以上的实现类,自然而然通过spi机制就可以直接添加被所承载的应用进行加载了,最后实现了引入依赖就自动被注册的动态效果!!
多参考一下大佬们的源码书写确实有一定帮助
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。