Spring Cloud Alibaba 使用RestTemplate进行服务消费

RocketMQ源码详解 | Broker篇 · 其二:文件系统 概述 在 Broker 的通用请求处理器将一个消息进行分发后,就来到了 Broker 的专门处理消息存储的业务处理器部分。本篇文章,我们将要探讨关于 RocketMQ 高效的原因之一:文件结构的良好设计与对 Page Cache 的极致"压榨"。 文件系统的结构设计 在 RocketMQ 的 Broker 中,有一类叫做 CommitLog 的文件,所有在该 Broker 上的 Topic 上的消息都会顺序的写入到这个文件中。 该消息的元信息存储着消息所在的 Topic 与 Queue。当消费者要进行消 阅读详情

概述

在 Broker 的通用请求处理器将一个消息进行分发后,就来到了 Broker 的专门处理消息存储的业务处理器部分。本篇文章,我们将要探讨关于 RocketMQ 高效的原因之一:文件结构的良好设计与对 Page Cache 的极致"压榨"。

文件系统的结构设计

在 RocketMQ 的 Broker 中,有一类叫做 CommitLog 的文件,所有在该 Broker 上的 Topic 上的消息都会顺序的写入到这个文件中。

该消息的元信息存储着消息所在的 Topic 与 Queue。当消费者要进行消费时,会通过 ConsumerQueue 文件来找到自己想要消费的队列。

该队列不存储具体的消息,而是存储消息的基本信息与偏移量。消费者通过偏移量去 CommitLog 中找到自己需要消费的信息然后取出,就可以进行消费。

并且,Broker 还可以对 CommitLog 来建立 Hash 索引文件 IndexFile,这样就可以通过 消息的 key 来找到消息。

官网上的这张图很好的表示了三类文件之间的关系。当然这章我们还是先只来看 CommitLog,其他两个留给下一章。



消息管理的结构层次

在学习 Broker 对于消息的处理时,我们可以跟着下面这张图走,这样可以对 Broker 的文件系统有一个清晰的了解

上图的主要思路来源于 该图 ,由于找不到原作者,故进行了重制与拓展


业务处理层

在 上一篇文章 中,我们看到在 BrokerController 中,SendMessageProcessor 注册了以下请求码

 
this.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendProcessor, this.sendMessageExecutor);

同时,在处理业务请求时,通用请求处理器是,通过调用 AsyncNettyRequestProcessor 的 asyncProcessRequest方法来处理连接和命令的,虽然也有同步的调用,但实际上大部分的业务处理 handler 都实现了异步的请求处理方法。

 
@Override
public void asyncProcessRequest(ChannelHandlerContext ctx, RemotingCommand request, RemotingResponseCallback responseCallback) throws Exception {
asyncProcessRequest(ctx, request).thenAcceptAsync(responseCallback::callback, this.brokerController.getSendMessageExecutor());
}

在 SendMessageProcessor 中,它首先是构造了一个异步处理方法(asyncProcessRequest),然后由自己的线程池去执行(thenAcceptAsync)。

根据上一章最后的那张线程模型的图,我们能知道构造这个异步方法和该方法的调用,都是通过自己的线程池来执行的,所以和同步执行的区别不是很大。

进入到异步方法的构造

 
public CompletableFuture<RemotingCommand> asyncProcessRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final SendMessageContext mqtraceContext;
switch (request.getCode()) {
case RequestCode.CONSUMER_SEND_MSG_BACK:
return this.asyncConsumerSendMsgBack(ctx, request);
default:
// 重建请求头
SendMessageRequestHeader requestHeader = parseRequestHeader(request);
if (requestHeader == null) {
return CompletableFuture.completedFuture(null);
}
// 构建 MQ trace 上下文
mqtraceContext = buildMsgContext(ctx, requestHeader);
this.executeSendMessageHookBefore(ctx, request, mqtraceContext);
if (requestHeader.isBatch()) {
return this.asyncSendBatchMessage(ctx, request, mqtraceContext, requestHeader);
} else {
return this.asyncSendMessage(ctx, request, mqtraceContext, requestHeader);
}
}
}

在这里对不同的请求进行分别处理,我们现在在意的是 SEND_MESSAGE ,所以先进入到 asyncSendMessage

 
// 重组
final RemotingCommand response = preSend(ctx, request, requestHeader);
// 构建响应头
final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader)response.readCustomHeader();
if (response.getCode() != -1) {
return CompletableFuture.completedFuture(response);
}
final byte[] body = request.getBody();
// 获取队列与 Topic 配置
int queueIdInt = requestHeader.getQueueId();
TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());
if (queueIdInt < 0) {
queueIdInt = randomQueueId(topicConfig.getWriteQueueNums());
}
// 以内部消息的格式存储
MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
msgInner.setTopic(requestHeader.getTopic());
msgInner.setQueueId(queueIdInt);
// 对于重试消息和延迟消息的处理
if (!handleRetryAndDLQ(requestHeader, response, request, msgInner, topicConfig)) {
return CompletableFuture.completedFuture(response);
}
msgInner.setBody(body);
/* pass:这里设置了一堆其他属性 */
CompletableFuture<PutMessageResult> putMessageResult = null;
String transFlag = origProps.get(MessageConst.PROPERTY_TRANSACTION_PREPARED);
if (transFlag != null && Boolean.parseBoolean(transFlag)) {
if (this.brokerController.getBrokerConfig().isRejectTransactionMessage()) {
response.setCode(ResponseCode.NO_PERMISSION);
response.setRemark(
"the broker[" + this.brokerController.getBrokerConfig().getBrokerIP1()
+ "] sending transaction message is forbidden");
return CompletableFuture.completedFuture(response);
}
putMessageResult = this.brokerController.getTransactionalMessageService().asyncPrepareMessage(msgInner);
} else {
putMessageResult = this.brokerController.getMessageStore().asyncPutMessage(msgInner);
}
// 对于写入结果,构造响应
return handlePutMessageResultFuture(putMessageResult, response, request, msgInner, responseHeader, mqtraceContext, ctx, queueIdInt);

在这里,它做了这几件事:

  1. 将消息通过内部消息(MessageExtBrokerInner)的格式保存
  2. 将重试消息、延时消息、事务消息由其他方法处理
  3. 除了完请求后,构造响应结果并返回

然后,我们进入了 Rocket 的存储组件层


存储组件层

这一层主要是负责操作下一层的逻辑文件对象来响应上一层的下发的请求。

工作的类是 MessageStore,主要的实现是 DefaultMessageStore

接着对"放入消息"这个命令来进行响应

 
// 检查持久化层的状态
PutMessageStatus checkStoreStatus = this.checkStoreStatus();
if (checkStoreStatus != PutMessageStatus.PUT_OK) {
return CompletableFuture.completedFuture(new PutMessageResult(checkStoreStatus, null));
}
// 检查消息正确
PutMessageStatus msgCheckStatus = this.checkMessage(msg);
if (msgCheckStatus == PutMessageStatus.MESSAGE_ILLEGAL) {
<
RocketMQ技术讲解V2.0 RocketMQ源码分析,分为存储篇、NameServer篇、Broker篇、Producer篇、Consumer篇五大部分进行源码级的讲解。大致如下: 1、讲解commitlog、consumequeue、index、transaction文件等数据结构、数据读写、HA高可用等功能; 2、讲解NameServer的启动、注册Broker、客户端查询Topic的路由信息等功能; 3、讲解Broker的启动、注册、处理Producer发送消息、处理Consumer拉取消息、事务消息的处理等功能; 4、讲解Producer端的启动、发送普通消息、定时消息、顺序消息、事务消息等功能; 5、讲解Consumer端的启动、PUSH模式的消息消费、PULL模式的消息消费、顺序消费/并发消费等功能; 立即下载

相关推荐

Contest 226 - C - Martial artist

from atcoder Problem Statement Time Limit: 2 sec / Memory Limit: 1024 MB Score :300300points Takahashi is a martial artist. There areNNmoves that a martial artist can learn, called Move11,22,\ldots…,NN. For each1 \leq i \leq N1≤i≤N, it takes...

m0_54674275的博客 1020

从爆仓到流畅发货:我们如何用EIQ分析给跨境小电商仓库做了一次‘体检’与‘手术’

本文分享了如何通过EIQ分析工具为跨境小电商仓库进行诊断与优化,从爆仓危机到流畅发货的实战经验。通过ABC分类法、动态路径算法等策略,拣货效率提升40%,错发率降低91%,日均处理能力翻倍。文章为小电商提供了轻量级工具选择和关键指标监控的实用建议。

weixin_28707739的博客 397

Python自动化脚本:模拟鼠标键盘保持电脑在线状态

在计算机自动化领域,模拟用户输入是一项基础且实用的技术,其核心原理是通过程序生成鼠标或键盘事件来与操作系统交互。这项技术的价值在于能够自动化重复性操作,提升工作效率,并解决特定场景下的系统交互问题。PyAutoGUI作为Python生态中广泛使用的自动化库,封装了跨平台的底层API调用,为开发者提供了简洁统一的接口来实现输入模拟。在实际工程实践中,这类技术常应用于自动化测试、远程办公辅助、数据抓取等场景,帮助用户保持系统活跃状态,防止因无操作导致的锁屏或休眠中断任务。通过合理配置移动间隔和随机化模式,可以更

weixin_28713299的博客 576

6-Halcon-- var_threshold 函数功能(用于基于局部统计特性的动态阈值分割的算子)

var_threshold 是 HALCON 中用于基于局部统计特性的动态阈值分割的算子,特别适用于处理低对比度图像或纹理均匀但包含细微差异的场景。与 dyn_threshold 不同,它不依赖预处理生成的参考图像,而是直接在局部区域内计算灰度值的统计特性(均值和标准差),从而自适应调整阈值。

weixin_45590420的博客 1326

基于STM32+ESP8266+手机APP的心率血氧温湿度监测报警系统设计(项目资料ID:18)

基于 STM32 微控制器、ESP8266 无线模块和 QT 手机 APP 的多参数监测报警系统。该系统可实时采集心率、血氧饱和度、环境温湿度等参数,通过 OLED 显示屏本地显示,并通过 WiFi 模块上传至手机 APP 实现远程监测与数据可视化。系统具备报警阈值自定义功能,当参数超出设定范围时,通过蜂鸣器和 LED 进行声光报警。系统以 STM32F103 为控制核心,采用 MAX30102 传感器采集心率和血氧,DHT20 采集温湿度,通过 ESP8266 实现无线通信,配合 QT 开发的手机 APP

以培养嵌入式工程师为己任 1万+

海德汉机床采集数据

海德汉数控系统我一般在高端机床上见得比较多。有好多五轴加工精度比较高的机床都用的是海德汉的系统。市面上常见的有530和640等型号。海德汉的采集还是有点难度的,需要对SDK有深度的了解。

若云流风的专栏 1525

【Power Compiler手册】4.saif文件

功耗计算的准确性取决于切换活动数据的准确性。这些数据是通过使用RTL仿真或门级仿真生成的,并存储在SAIF文件中。在执行功耗优化和分析之前,应该使用SAIF文件来反标设计对象上的切换活动信息。SAIF是由Synopsys支持的ASCII格式,用于促进不同Synopsys工具之间的信息交换(参见IEEE 1801标准,附录J)。使用`read_saif`命令读取SAIF文件,使用`write_saif`命令写出SAIF文件。有关更多信息,请参见`read_saif`和`write_saif`命令的手册页。

QRBQ 2186

【安全启动】HSM安全启动系统学习指南

HSM安全启动系统学习指南摘要 本指南为工程师提供关于HSM安全启动的系统性学习路径,以英飞凌AURIX TC377芯片为核心案例,涵盖基础理论、芯片实现、开发实践和行业应用四个阶段。安全启动作为设备信任链的起点,在汽车电子和工业控制领域尤为重要。指南详细解析了TC377的HSM架构、UCB/PROCON配置、密钥管理等关键技术,并提供了从开发到认证的全流程指导。特别关注汽车行业合规要求(如ISO/SAE 21434、UN R155),帮助开发者构建安全可靠的启动系统,规避常见工程陷阱。通过四阶段渐进学习,

weixin_46481662的博客 515

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

上一篇: Kubernetes Deployment 源码分析(一)
下一篇: 议题解析与复现--Java内存攻击技术漫谈
Java在我心中永远的神
博客等级 码龄6年 1535粉丝 111原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值