rocketmq 初探(二)

大家好,我是烤鸭:

    上一篇简单介绍和rocketmq,这一篇看下源码之注册中心。

namesrv

先看两个初始化方法
NamesrvController.initialize() 和 NettyRemotingServer.start();

public boolean initialize() {// 加载配置文件this.kvConfigManager.load();// 创建 NettyRemotingServer 并初始化参数this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);this.remotingExecutor =Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));// 将刚才的线程池和netty server 绑定this.registerProcessor();// 每隔10s检测最近120s不活跃的broker并移除this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {NamesrvController.this.routeInfoManager.scanNotActiveBroker();}}, 5, 10, TimeUnit.SECONDS);// 每隔10分钟输出一下配置this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {NamesrvController.this.kvConfigManager.printAllPeriodically();}}, 1, 10, TimeUnit.MINUTES);// 如果想用tls,ssl协议的话,需要证书构造 sslContextif (TlsSystemConfig.tlsMode != TlsMode.DISABLED) {// Register a listener to reload SslContexttry {fileWatchService = new FileWatchService(new String[] {TlsSystemConfig.tlsServerCertPath,TlsSystemConfig.tlsServerKeyPath,TlsSystemConfig.tlsServerTrustCertPath},new FileWatchService.Listener() {boolean certChanged, keyChanged = false;@Overridepublic void onChanged(String path) {if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) {log.info("The trust certificate changed, reload the ssl context");reloadServerSslContext();}if (path.equals(TlsSystemConfig.tlsServerCertPath)) {certChanged = true;}if (path.equals(TlsSystemConfig.tlsServerKeyPath)) {keyChanged = true;}if (certChanged && keyChanged) {log.info("The certificate and private key changed, reload the ssl context");certChanged = keyChanged = false;reloadServerSslContext();}}private void reloadServerSslContext() {((NettyRemotingServer) remotingServer).loadSslContext();}});} catch (Exception e) {log.warn("FileWatchService created error, can't load the certificate dynamically");}}return true;
}

NettyRemotingServer.start()

public void start() {// 用刚才初始化的线程池创建线程this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(),new ThreadFactory() {private AtomicInteger threadIndex = new AtomicInteger(0);@Overridepublic Thread newThread(Runnable r) {return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());}});// 构建netty 相关的handler,包含连接、读数据、解码、请求和响应处理prepareSharableHandlers();// 创建netty server,使用初始化的参数和刚才的handler初始化channelServerBootstrap childHandler =this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()).childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()).localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(defaultEventExecutorGroup, HANDSHAKE_HANDLER_NAME, handshakeHandler).addLast(defaultEventExecutorGroup,encoder,new NettyDecoder(),new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),connectionManageHandler,serverHandler);}});if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);}try {ChannelFuture sync = this.serverBootstrap.bind().sync();InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();this.port = addr.getPort();} catch (InterruptedException e1) {throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);}// 启动channel的监听器,针对channel的连接、关闭、异常、空闲(后面其他的实现都是关闭逻辑)if (this.channelEventListener != null) {this.nettyEventExecutor.start();}// 每秒处理过时的响应,如果超时时间+1秒没响应,就移除该请求并手动回调(由于注册中心没有对外发请求,所以没用到,client和server用到了)this.timer.scheduleAtFixedRate(new TimerTask() {从@Overridepublic void run() {try {NettyRemotingServer.this.scanResponseTable();} catch (Throwable e) {log.error("scanResponseTable exception", e);}}}, 1000 * 3, 1000);
}

再看下 NettyClientHandler,对请求和响应指令进行处理

/*** Entry of incoming command processing.** <p>* <strong>Note:</strong>* The incoming remoting command may be* <ul>* <li>An inquiry request from a remote peer component;</li>* <li>A response to a previous request issued by this very participant.</li>* </ul>* </p>** @param ctx Channel handler context.* @param msg incoming remoting command.* @throws Exception if there were any error while processing the incoming command.*/
public void processMessageReceived(ChannelHandlerContext ctx, RemotingCommand msg) throws Exception {final RemotingCommand cmd = msg;if (cmd != null) {switch (cmd.getType()) {case REQUEST_COMMAND:// 接收请求并处理processRequestCommand(ctx, cmd);break;case RESPONSE_COMMAND:// 接收响应,维护responseTable(注册中心用不到)processResponseCommand(ctx, cmd);break;default:break;}}
}

由于注册中心没有发起 request,看下 processRequestCommand(接收request)

/*** Process incoming request command issued by remote peer.** @param ctx channel handler context.* @param cmd request command.*/
public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) {// request的code在 RequestCode 类维护,包括 发送、拉取等等final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor : matched;// 自增计数final int opaque = cmd.getOpaque();if (pair != null) {Runnable run = new Runnable() {@Overridepublic void run() {try {// ACL鉴权 (client端和broker使用)doBeforeRpcHooks(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);final RemotingResponseCallback callback = new RemotingResponseCallback() {@Overridepublic void callback(RemotingCommand response) {doAfterRpcHooks(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd, response);if (!cmd.isOnewayRPC()) {if (response != null) {response.setOpaque(opaque);response.markResponseType();try {ctx.writeAndFlush(response);} catch (Throwable e) {log.error("process request over, but response failed", e);log.error(cmd.toString());log.error(response.toString());}} else {}}}};// 异步 or 同步if (pair.getObject1() instanceof AsyncNettyRequestProcessor) {AsyncNettyRequestProcessor processor = (AsyncNettyRequestProcessor)pair.getObject1();processor.asyncProcessRequest(ctx, cmd, callback);} else {NettyRequestProcessor processor = pair.getObject1();// 比较重要的地方,单独分析RemotingCommand response = processor.processRequest(ctx, cmd);callback.callback(response);}} catch (Throwable e) {log.error("process request exception", e);log.error(cmd.toString());if (!cmd.isOnewayRPC()) {final RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_ERROR,RemotingHelper.exceptionSimpleDesc(e));response.setOpaque(opaque);ctx.writeAndFlush(response);}}}};// 系统繁忙,注册中心不会提示这个(broker 刷盘不及时会报这个)if (pair.getObject1().rejectRequest()) {final RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_BUSY,"[REJECTREQUEST]system busy, start flow control for a while");response.setOpaque(opaque);ctx.writeAndFlush(response);return;}try {final RequestTask requestTask = new RequestTask(run, ctx.channel(), cmd);pair.getObject2().submit(requestTask);} catch (RejectedExecutionException e) {// 避免日志打印的太多if ((System.currentTimeMillis() % 10000) == 0) {log.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel())+ ", too many requests and system thread pool busy, RejectedExecutionException "+ pair.getObject2().toString()+ " request code: " + cmd.getCode());}// 不是单向请求(onewayRPC,线程池满的话,直接返回系统繁忙)if (!cmd.isOnewayRPC()) {final RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_BUSY,"[OVERLOAD]system busy, start flow control for a while");response.setOpaque(opaque);ctx.writeAndFlush(response);}}} else {String error = " request type " + cmd.getCode() + " not supported";final RemotingCommand response =RemotingCommand.createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);response.setOpaque(opaque);ctx.writeAndFlush(response);log.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);}
}

我们先看一下 NettyRequestProcessor.processRequest 实现

在这里插入图片描述

DefaultRequestProcessor.processRequest

其实看名字就能看出来 注册中心的操作了

public RemotingCommand processRequest(ChannelHandlerContext ctx,RemotingCommand request) throws RemotingCommandException {if (ctx != null) {log.debug("receive request, {} {} {}",request.getCode(),RemotingHelper.parseChannelRemoteAddr(ctx.channel()),request);}switch (request.getCode()) {case RequestCode.PUT_KV_CONFIG:// admin调用,配置添加到 configTable,定期打印return this.putKVConfig(ctx, request);case RequestCode.GET_KV_CONFIG:// admin调用,获取配置return this.getKVConfig(ctx, request);case RequestCode.DELETE_KV_CONFIG:// admin调用,删除配置return this.deleteKVConfig(ctx, request);case RequestCode.QUERY_DATA_VERSION:// broker 获取topic配置return queryBrokerTopicConfig(ctx, request);case RequestCode.REGISTER_BROKER:// 注册broker,版本不同处理逻辑有些不一样(topic配置信息封装不同)Version brokerVersion = MQVersion.value2Version(request.getVersion());if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {return this.registerBrokerWithFilterServer(ctx, request);} else {return this.registerBroker(ctx, request);}case RequestCode.UNREGISTER_BROKER:// 下线 brokerreturn this.unregisterBroker(ctx, request);case RequestCode.GET_ROUTEINFO_BY_TOPIC:// 根据topic获取路由信息,获取的key是 ORDER_TOPIC_CONFIG+topicidreturn this.getRouteInfoByTopic(ctx, request);case RequestCode.GET_BROKER_CLUSTER_INFO:// 获取broker 集群信息return this.getBrokerClusterInfo(ctx, request);case RequestCode.WIPE_WRITE_PERM_OF_BROKER:// 废除broker的写入权限return this.wipeWritePermOfBroker(ctx, request);case RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER:// 获取所有的topicreturn getAllTopicListFromNameserver(ctx, request);case RequestCode.DELETE_TOPIC_IN_NAMESRV:// 删除topicreturn deleteTopicInNamesrv(ctx, request);case RequestCode.GET_KVLIST_BY_NAMESPACE:// 根据namespace获取配置return this.getKVListByNamespace(ctx, request);case RequestCode.GET_TOPICS_BY_CLUSTER:// 根据cluster下的broker获取topicreturn this.getTopicsByCluster(ctx, request);case RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS:// 获取cluster、broker和关联信息return this.getSystemTopicListFromNs(ctx, request);case RequestCode.GET_UNIT_TOPIC_LIST:// 设置unit_mode true && 非重试的时候,这个配置好像没用啊(https://github.com/apache/rocketmq/issues/639)return this.getUnitTopicList(ctx, request);case RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST:// 设置unit_mode true(校验消息和心跳的时候),获取topicreturn this.getHasUnitSubTopicList(ctx, request);case RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST:// !getUnitTopicList && getHasUnitSubTopicListreturn this.getHasUnitSubUnUnitTopicList(ctx, request);case RequestCode.UPDATE_NAMESRV_CONFIG:// 更新注册中心配置return this.updateConfig(ctx, request);case RequestCode.GET_NAMESRV_CONFIG:// 获取注册中心配置return this.getConfig(ctx, request);default:break;}return null;
}

小结

注册中心的作用:

存了 cluster、broker、topic的信息。

提供了一些接口,可以broker注册和下线,修改配置等。

检测和维护broker是否活跃。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/412519.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[css] 说说你对line-height是如何理解的?

[css] 说说你对line-height是如何理解的&#xff1f; line-height 行高&#xff0c;就是两行文字之间基线的距离&#xff0c;用来调整文字的行间距。个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 …

2 JVM 运行机制

转载于:https://www.cnblogs.com/likevin/p/10186591.html

[css] 要让Chrome支持小于12px的文字怎么做?

[css] 要让Chrome支持小于12px的文字怎么做&#xff1f; 1, 改用图片 2, 使用 -webkit-text-size-adjust:none; 但是不支持chrome 27.0以上版本 3, 使用 transform: scale( )缩小 暂时不知道更多方法了个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易…

rocketmq 初探(三)

大家好&#xff0c;我是烤鸭&#xff1a; 上一篇介绍了注册中心&#xff0c;这一篇看下broker。基于 rocketmq 4.9 版本。 BrokerStartup#BrokerController 按照代码的先后顺序撸源码&#xff1a; BrokerController.createBrokerController public static BrokerController…

WIN10远程连接时提示内部错误

微软官方的解决方案是重置远程连接设置&#xff0c;步骤如下&#xff1a; 1、以管理员身份运行命令提示符 2、输入以下命令&#xff1a; netsh winsoc reset 随后会提示重启电脑&#xff0c;遂解决。 3、重启后还不行的话&#xff0c;再试试删除掉远程连接保存的凭据&#xff0…

[css] css的属性content有什么作用呢?有哪些场景可以用到?

[css] css的属性content有什么作用呢&#xff1f;有哪些场景可以用到&#xff1f; content属性与 ::before 及 ::after 伪元素配合使用生成文本内容通过attr()将选择器对象的属性作为字符串进行显示&#xff0c;如&#xff1a;a::after{content: attr(href)} <a href"h…

rocketmq 初探(四)

大家好&#xff0c;我是烤鸭&#xff1a; 上一篇简单介绍broker的初始化&#xff0c;这一篇介绍 NettyRequestProcessor 的实现(主要是broker里用到的)。 AdminBrokerProcessor、ClientManageProcessor、ConsumerManageProcessor、EndTransactionProcessor NettyRequestProce…

iOS 去除警告 看我就够了

你是不是看着开发过程中出现的一堆的警告会心情一阵烦躁&#xff0c;别烦躁了&#xff0c;看完此文章&#xff0c;消除警告的小尾巴。 一、SVN 操作导致的警告 1.svn删除文件后报错 ”xx“is missing from working copy 使用命令sudo find 工程项目路径 -name ".svn"…

[css] 什么是FOUC?你是如何避免FOUC的?

[css] 什么是FOUC&#xff1f;你是如何避免FOUC的&#xff1f; FOUC 即 Flash of Unstyled Content&#xff0c;是指页面一开始以样式 A&#xff08;或无样式&#xff09;的渲染&#xff0c;突然变成样式B。 原因是样式表的晚于 HTML 加载导致页面重新进行绘制。通过 import 方…

rocketmq 初探(五)

大家好&#xff0c;我是烤鸭&#xff1a; 上一篇简单介绍部分 NettyRequestProcessor (AdminBrokerProcessor、ClientManageProcessor、ConsumerManageProcessor、EndTransactionProcessor)&#xff0c;这一篇介绍其他的。 PullMessageProcessor、QueryMessageProcessor、Repl…

Python 装饰器初探

Python 装饰器初探 在谈及Python的时候&#xff0c;装饰器一直就是道绕不过去的坎。面试的时候&#xff0c;也经常会被问及装饰器的相关知识。总感觉自己的理解很浅显&#xff0c;不够深刻。是时候做出改变&#xff0c;对Python的装饰器做个全面的了解了。 1. 函数装饰器 直接上…

[css] 解释下 CSS sprites的原理和优缺点分别是什么

[css] 解释下 CSS sprites的原理和优缺点分别是什么 我来说下我的观点 原理&#xff1a; 多张图合并成一张图优点&解决的问题hover效果&#xff0c;如果是多个图片&#xff0c;网络正常的情况下首次会闪烁一下。如果是断网情况下&#xff0c;就没图片了。sprites 就很好的…

《自律100天,穿越人生盲点》读书笔记

大家好&#xff0c;我是烤鸭&#xff1a; 《自律100天&#xff0c;穿越人生盲点》&#xff0c;读书笔记。 第一章 “自律100天”的华丽开启 第一节 “自律100天”的底层逻辑 习惯没办法用金钱换&#xff0c;只能用时间。 训练延迟满足(增强自控、培养耐心、减少短期诱惑…

递推数列

题目描述 给定a0,a1,以及anpa(n-1) qa(n-2)中的p,q。这里n > 2。 求第k个数对10000的模。 输入描述: 输入包括5个整数&#xff1a;a0、a1、p、q、k。 输出描述: 第k个数a(k)对10000的模。 分析 循环求出ak即可 #include <iostream>using namespace std;int main(){in…

[css] 请描述margin边界叠加是什么及解决方案

[css] 请描述margin边界叠加是什么及解决方案 1&#xff0c;使用padding代替&#xff0c;但是父盒子要减去相应的高度 2&#xff0c;使用boder&#xff08;透明&#xff09;代替&#xff08;不推荐&#xff0c;不符合书写规范&#xff0c;如果父盒子子盒子时有颜色的不好处理&…

从线上慢sql看explain关键字

大家好&#xff0c;我是烤鸭&#xff1a; 最近有点忙的头晕&#xff0c;又懒又累&#xff0c;正好线上遇到慢sql的问题&#xff0c;就说下 MySQL Explain 关键字的解析和使用示例。 explain 关键字说明 使用explain关键字可以模拟优化器执行sql查询语句&#xff0c;从而得…

[css] style标签写在body前和body后的区别是什么?

[css] style标签写在body前和body后的区别是什么&#xff1f; 渲染机制的区别&#xff0c;在body前是已经把样式浏览一遍&#xff0c;到了对应标签直接&#xff0c;渲染样式。显示块。 在body后&#xff0c;是浏览器已经把标签浏览了&#xff0c;但基于没有样式&#xff0c;显…

自然语言处理的一些链接

Word2Vec Tutorial - The Skip-Gram ModelVisualizing A Neural Machine Translation Model (Mechanics of Seq2seq Models With Attention) 转载于:https://www.cnblogs.com/linyihai/p/10200351.html

《Java并发编程实践-第一部分》-读书笔记

大家好&#xff0c;我是烤鸭&#xff1a; 《Java并发编程实战-第一部分》-读书笔记。 第一章&#xff1a;介绍 1.1 并发历史&#xff1a; 多个程序在各自的进程中执行&#xff0c;由系统分配资源&#xff0c;如&#xff1a;内存、文件句柄、安全证书。进程间通信方式&#x…

[css] 说说你对css盒子模型的理解

[css] 说说你对css盒子模型的理解 css盒模型由两个盒子组成&#xff0c;外在的控制是否换行的盒子&#xff0c;以及内在的控制元素内容的盒子。比如&#xff1a;display: inline-block, 则它的外在的盒子就是inline也就是不占据一行&#xff0c;而block则表示内部的元素具有块状…