---
title: " MetaQ技术内幕——源码分析(八)"
author: "wbj0110"
date: "2014-06-01T10:36:05Z"
tags: ["metaq"]
categories: ["编程语言"]
slug: "metaq"
draft: false
lastmod: "2014-06-01T10:36:02Z"
id: 2074348
url: "https://soledede.iteye.com/blog/2074348"
---

上一篇以及上上篇基本介绍了MetaQ如何使用Gecko框架在网络上传输数据，今天将继续进一步介绍在Broker，各种命令的处理逻辑（暂时将不涉及到事务处理）。

依旧是在MetaMorphosisBroker的registerProcessors()方法中，我们可以注意到一点，每个Processor的实例在构造的时候都注入了一个brokerProcessor的变量，该变量的类型为CommandProcessor。其实，各个Processor的业务逻辑又委托给了CommandProcessor进行处理，比如我们看看其中的GetProcessor的源码：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1936194 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23441755 "收藏这段代码")

01. public class GetProcessor implements RequestProcessor&lt;GetCommand&gt; {
02. public static final Logger log = LoggerFactory.getLogger(GetProcessor.class);
03. private final ThreadPoolExecutor executor;
04. private final CommandProcessor processor;
05. public GetProcessor(final CommandProcessor processor, final ThreadPoolExecutor executor) {
06. this.processor = processor;
07. this.executor = executor;
08. }
09. @Override
10. public ThreadPoolExecutor getExecutor() {
11. return this.executor;
12. }
13. @Override
14. public void handleRequest(final GetCommand request, final Connection conn) {
15. // Processor并没有处理具体的业务逻辑，而是将业务逻辑交给CommandProcessor的processGetCommand()进行处理，Processor只是将处理结果简单的返回给客户端
16. final ResponseCommand response = this.processor.processGetCommand(request, SessionContextHolder.getOrCreateSessionContext(conn, null));
17. if (response != null) {
18. RemotingUtils.response(conn, response);
19. }
20. }
21. }

```
public class GetProcessor implements RequestProcessor<GetCommand> {	public static final Logger log = LoggerFactory.getLogger(GetProcessor.class);	private final ThreadPoolExecutor executor;	private final CommandProcessor processor;	public GetProcessor(final CommandProcessor processor, final ThreadPoolExecutor executor) {		this.processor = processor;		this.executor = executor;	}	@Override	public ThreadPoolExecutor getExecutor() {		return this.executor;	}	@Override	public void handleRequest(final GetCommand request, final Connection conn) {		// Processor并没有处理具体的业务逻辑，而是将业务逻辑交给CommandProcessor的processGetCommand()进行处理，Processor只是将处理结果简单的返回给客户端final ResponseCommand response = this.processor.processGetCommand(request, SessionContextHolder.getOrCreateSessionContext(conn, null));		if (response != null) {			RemotingUtils.response(conn, response);		}	}}
```

CommandProcessor业务逻辑的处理模块采用责任链的处理方式，目前来说只有两个类型的业务逻辑处理单元：带有事务处理(TransactionalCommandProcessor)的和不带有事务处理(BrokerCommandProcessor)的。老习惯，先上类图：

![](http://dl2.iteye.com/upload/attachment/0088/9540/c00aefd3-b130-3134-9773-4e12f0735425.jpg)

CommandProcessor接口定义如下：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1936194 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23441755 "收藏这段代码")

01. public interface CommandProcessor extends Service {
02. //处理Put命令，结果通过PutCallback的回调返回
03. public void processPutCommand(final PutCommand request, final SessionContext sessionContext, final PutCallback cb) throws Exception;
04. //处理Get命令
05. public ResponseCommand processGetCommand(GetCommand request, final SessionContext ctx);
06. /\**
07. \* Under conditions that cannot use notify-remoting directly.
08. \*/
09. //处理Get命令，并根据条件zeroCopy是否使用zeroCopy
10. public ResponseCommand processGetCommand(GetCommand request, final SessionContext ctx, final boolean zeroCopy);
11. //处理查询最近可用offset位置请求
12. public ResponseCommand processOffsetCommand(OffsetCommand request, final SessionContext ctx);
13. //处理退出请求
14. public void processQuitCommand(QuitCommand request, final SessionContext ctx);
15. public ResponseCommand processVesionCommand(VersionCommand request, final SessionContext ctx);
16. //处理统计请求
17. public ResponseCommand processStatCommand(StatsCommand request, final SessionContext ctx);
18. //下面主要定义与事务相关的方法，暂时先不介绍
19. public void removeTransaction(final XATransactionId xid);
20. public Transaction getTransaction(final SessionContext context, final TransactionId xid) throws MetamorphosisException, XAException;
21. public void forgetTransaction(final SessionContext context, final TransactionId xid) throws Exception;
22. public void rollbackTransaction(final SessionContext context, final TransactionId xid) throws Exception;
23. public void commitTransaction(final SessionContext context, final TransactionId xid, final boolean onePhase) throws Exception;
24. public int prepareTransaction(final SessionContext context, final TransactionId xid) throws Exception;
25. public void beginTransaction(final SessionContext context, final TransactionId xid, final int seconds) throws Exception;
26. public TransactionId\[] getPreparedTransactions(final SessionContext context, String uniqueQualifier) throws Exception;
27. }

```
public interface CommandProcessor extends Service {    //处理Put命令，结果通过PutCallback的回调返回	public void processPutCommand(final PutCommand request, final SessionContext sessionContext, final PutCallback cb) throws Exception;     //处理Get命令	public ResponseCommand processGetCommand(GetCommand request, final SessionContext ctx);	/**	 * Under conditions that cannot use notify-remoting directly.	 */     //处理Get命令，并根据条件zeroCopy是否使用zeroCopy	public ResponseCommand processGetCommand(GetCommand request, final SessionContext ctx, final boolean zeroCopy);    //处理查询最近可用offset位置请求	public ResponseCommand processOffsetCommand(OffsetCommand request, final SessionContext ctx);    //处理退出请求	public void processQuitCommand(QuitCommand request, final SessionContext ctx);   	public ResponseCommand processVesionCommand(VersionCommand request, final SessionContext ctx);    //处理统计请求	public ResponseCommand processStatCommand(StatsCommand request, final SessionContext ctx);    //下面主要定义与事务相关的方法，暂时先不介绍	public void removeTransaction(final XATransactionId xid);	public Transaction getTransaction(final SessionContext context, final TransactionId xid) throws MetamorphosisException, XAException;	public void forgetTransaction(final SessionContext context, final TransactionId xid) throws Exception;	public void rollbackTransaction(final SessionContext context, final TransactionId xid) throws Exception;	public void commitTransaction(final SessionContext context, final TransactionId xid, final boolean onePhase) throws Exception;	public int prepareTransaction(final SessionContext context, final TransactionId xid) throws Exception;	public void beginTransaction(final SessionContext context, final TransactionId xid, final int seconds) throws Exception;	public TransactionId[] getPreparedTransactions(final SessionContext context, String uniqueQualifier) throws Exception;}
```

细心的读者会发现，每个定义的方法的参数都有一个参数SessionContext，SessionContext携带了连接的信息，由Broker创建，具体代码见SessionContextHolder的getOrCreateSessionContext()方法，getOrCreateSessionContext()方法在Processor委托给CommandProcessor处理业务逻辑时被调用。

BrokerCommandProcessor和TransactionalCommandProcessor其实就是各模块的粘合剂，将各模块的功能统一协调形成整体对外提供功能。BrokerCommandProcessor的实现并不难理解，下面让我们来具体分析一下BrokerCommandProcessor这个类：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1936194 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23441755 "收藏这段代码")

001. //Put请求的业务逻辑处理
002. @Override
003. public void processPutCommand(final PutCommand request, final SessionContext sessionContext, final PutCallback cb) {
004. final String partitionString = this.metaConfig.getBrokerId() + "-" + request.getPartition();
005. //统计计算
006. this.statsManager.statsPut(request.getTopic(), partitionString, 1);
007. this.statsManager.statsMessageSize(request.getTopic(), request.getData().length);
008. int partition = -1;
009. try {
010. //如果对应存储的分区已经关闭，则拒绝该消息
011. if (this.metaConfig.isClosedPartition(request.getTopic(), request.getPartition())) {
012. log.warn("Can not put message to partition " + request.getPartition() + " for topic=" + request.getTopic() + ",it was closed");
013. if (cb != null) {
014. cb.putComplete(new BooleanCommand(HttpStatus.Forbidden, this.genErrorMessage(request.getTopic(), request.getPartition()) + "Detail:partition\[" + partitionString + "] has been closed", request.getOpaque()));
015. }
016. return;
017. }
018. partition = this.getPartition(request);
019. //获取对应Topic分区的MessageStore实例
020. final MessageStore store = this.storeManager.getOrCreateMessageStore(request.getTopic(), partition);
021. // 如果是动态添加的topic，需要注册到zk
022. //就到目前为止，我着实没想明白下面这句代码的用途是什么？
023. //如果topic没有在该Broker的配置中配置，在MessageStoreManager中的isLegalTopic()方法中检查就通不过而抛出异常，那么下面这句代码怎么样都不会被执行，而Client要向Broker发送消息，一定要先发布topic，保证topic在zk发布；
024. this.brokerZooKeeper.registerTopicInZk(request.getTopic(), false);
025. // 设置唯一id
026. final long messageId = this.idWorker.nextId();
027. //存储消息，之前的文章介绍过Broker的存储使用回调的方式，易于异步的实现，代码简单不分析
028. store.append(messageId, request, new StoreAppendCallback(partition, partitionString, request, messageId, cb));
029. } catch (final Exception e) {
030. //发生异常，统计计算回滚
031. this.statsManager.statsPutFailed(request.getTopic(), partitionString, 1);
032. log.error("Put message failed", e);
033. if (cb != null) {
034. //返回结果
035. cb.putComplete(new BooleanCommand(HttpStatus.InternalServerError, this.genErrorMessage(request.getTopic(), partition) + "Detail:" + e.getMessage(), request.getOpaque()));
036. }
037. }
038. }
039. @Override
040. // GET请求的业务逻辑处理
041. public ResponseCommand processGetCommand(final GetCommand request, final SessionContext ctx) {
042. //默认为zeroCopy
043. return this.processGetCommand(request, ctx, true);
044. }
045. @Override
046. public ResponseCommand processGetCommand(final GetCommand request, final SessionContext ctx, final boolean zeroCopy) {
047. //获取查询信息
048. final String group = request.getGroup();
049. final String topic = request.getTopic();
050. //统计计数（请求数统计）
051. this.statsManager.statsGet(topic, group, 1);
052. // 如果分区被关闭,禁止读数据 --wuhua
053. if (this.metaConfig.isClosedPartition(topic, request.getPartition())) {
054. log.warn("can not get message for topic=" + topic + " from partition " + request.getPartition() + ",it closed,");
055. return new BooleanCommand(HttpStatus.Forbidden, "Partition\[" + this.metaConfig.getBrokerId() + "-" + request.getPartition() + "] has been closed", request.getOpaque());
056. }
057. //获取topic对应分区的MessageStore实例，如果实例不存在，则返回NotFound
058. final MessageStore store = this.storeManager.getMessageStore(topic, request.getPartition());
059. if (store == null) {
060. //统计计数
061. this.statsManager.statsGetMiss(topic, group, 1);
062. return new BooleanCommand(HttpStatus.NotFound, "The topic \`" + topic + "\` in partition \`" + request.getPartition() + "\` is not exists", request.getOpaque());
063. }
064. //如果请求的起始位置&lt;0，判定该请求无效
065. if (request.getMaxSize() &lt;= 0) {
066. return new BooleanCommand(HttpStatus.BadRequest, "Bad request,invalid max size:" + request.getMaxSize(), request.getOpaque());
067. }
068. try {
069. //读取由request.getOffset()开始的消息集合
070. final MessageSet set = store.slice(request.getOffset(), Math.min(this.metaConfig.getMaxTransferSize(), request.getMaxSize()));
071. //如果当前消息集不为空
072. if (set != null) {
073. //判断是否zeroCopy，如果是zeroCopy，则直接写；如果不是，则将消息集包装成DataCommand，这也就是前面为什么说DataCommand要实现encode()方法的缘故
074. if (zeroCopy) {
075. set.write(request, ctx);
076. return null;
077. } else {
078. // refer to the code of line 440 in MessageStore
079. // create two copies of byte array including the byteBuffer
080. // and new bytes
081. // this may not a good use case of Buffer
082. final ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(this.metaConfig.getMaxTransferSize(), request.getMaxSize()));
083. set.read(byteBuffer);
084. byteBuffer.flip();
085. final byte\[] bytes = new byte\[byteBuffer.remaining()];
086. byteBuffer.get(bytes);
087. return new DataCommand(bytes, request.getOpaque());
088. }
089. } else {
090. //如果为空消息集，则认为请求无效
091. //统计计数
092. this.statsManager.statsGetMiss(topic, group, 1);
093. this.statsManager.statsGetFailed(topic, group, 1);
094. // 当请求的偏移量大于实际最大值时,返回给客户端实际最大的偏移量.
095. final long maxOffset = store.getMaxOffset();
096. final long requestOffset = request.getOffset();
097. if (requestOffset &gt; maxOffset && (this.metaConfig.isUpdateConsumerOffsets() || requestOffset == Long.MAX\_VALUE)) {
098. log.info("offset\[" + requestOffset + "] is exceeded,tell the client real max offset: " + maxOffset + ",topic=" + topic + ",group=" + group);
099. this.statsManager.statsOffset(topic, group, 1);
100. return new BooleanCommand(HttpStatus.Moved, String.valueOf(maxOffset), request.getOpaque());
101. } else {
102. return new BooleanCommand(HttpStatus.NotFound, "Could not find message at position " + requestOffset, request.getOpaque());
103. }
104. }
105. } catch (final ArrayIndexOutOfBoundsException e) {
106. log.error("Could not get message from position " + request.getOffset() + ",it is out of bounds,topic=" + topic);
107. // 告知最近可用的offset
108. this.statsManager.statsGetMiss(topic, group, 1);
109. this.statsManager.statsGetFailed(topic, group, 1);
110. final long validOffset = store.getNearestOffset(request.getOffset());
111. this.statsManager.statsOffset(topic, group, 1);
112. return new BooleanCommand(HttpStatus.Moved, String.valueOf(validOffset), request.getOpaque());
113. } catch (final Throwable e) {
114. log.error("Could not get message from position " + request.getOffset(), e);
115. this.statsManager.statsGetFailed(topic, group, 1);
116. return new BooleanCommand(HttpStatus.InternalServerError, this.genErrorMessage(request.getTopic(), request.getPartition()) + "Detail:" + e.getMessage(), request.getOpaque());
117. }
118. }
119. //查询最近可用offset请求的业务逻辑处理
120. @Override
121. public ResponseCommand processOffsetCommand(final OffsetCommand request, final SessionContext ctx) {
122. //统计计数
123. this.statsManager.statsOffset(request.getTopic(), request.getGroup(), 1);
124. //获取topic对应分区的MessageStore实例
125. final MessageStore store = this.storeManager.getMessageStore(request.getTopic(), request.getPartition());
126. //如果为空，则返回未找到
127. if (store == null) {
128. return new BooleanCommand(HttpStatus.NotFound, "The topic \`" + request.getTopic() + "\` in partition \`" + request.getPartition() + "\` is not exists", request.getOpaque());
129. }
130. //获取topic对应分区最近可用的offset
131. final long offset = store.getNearestOffset(request.getOffset());
132. return new BooleanCommand(HttpStatus.Success, String.valueOf(offset), request.getOpaque());
133. }
134. //退出请求业务逻辑处理
135. @Override
136. public void processQuitCommand(final QuitCommand request, final SessionContext ctx) {
137. try {
138. if (ctx.getConnection() != null) {
139. //关闭与客户端的连接
140. ctx.getConnection().close(false);
141. }
142. } catch (final NotifyRemotingException e) {
143. // ignore
144. }
145. }
146. //版本查询请求业务逻辑处理
147. @Override
148. public ResponseCommand processVesionCommand(final VersionCommand request, final SessionContext ctx) {
149. //返回当前Broker版本
150. return new BooleanCommand(HttpStatus.Success, BuildProperties.VERSION, request.getOpaque());
151. }
152. //统计请求查询业务逻辑处理
153. @Override
154. public ResponseCommand processStatCommand(final StatsCommand request, final SessionContext ctx) {
155. //判断类型，如果类型以config 开头，则传输整个配置文件
156. final String item = request.getItem();
157. if ("config".equals(item)) {
158. return this.processStatsConfig(request, ctx);
159. } else {
160. //如果是获取统计结果，则从统计模块获取响应结果并返回给客户端
161. final String statsInfo = this.statsManager.getStatsInfo(item);
162. return new BooleanCommand(HttpStatus.Success, statsInfo, request.getOpaque());
163. }
164. }
165. //获取配置文件内容，使用zeroCopy将文件内容发送到客户端，构造的响应用BooleanCommand
166. @SuppressWarnings("resource")
167. private ResponseCommand processStatsConfig(final StatsCommand request, final SessionContext ctx) {
168. try {
169. final FileChannel fc = new FileInputStream(this.metaConfig.getConfigFilePath()).getChannel();
170. // result code length opaque\\r\\n
171. IoBuffer buf = IoBuffer.allocate(11 + 3 + ByteUtils.stringSize(fc.size()) + ByteUtils.stringSize(request.getOpaque()));
172. ByteUtils.setArguments(buf, MetaEncodeCommand.RESULT\_CMD, HttpStatus.Success, fc.size(), request.getOpaque());
173. buf.flip();
174. ctx.getConnection().transferFrom(buf, null, fc, 0, fc.size(), request.getOpaque(),
175. new SingleRequestCallBackListener() {
176. @Override
177. public void onResponse(ResponseCommand responseCommand, Connection conn) {
178. this.closeChannel();
179. }
180. @Override
181. public void onException(Exception e) {
182. this.closeChannel();
183. }
184. private void closeChannel() {
185. try {
186. fc.close();
187. } catch (IOException e) {
188. log.error("IOException while stats config", e);
189. }
190. }
191. @Override
192. public ThreadPoolExecutor getExecutor() {
193. return null;
194. }
195. }, 5000, TimeUnit.MILLISECONDS);
196. } catch (FileNotFoundException e) {
197. log.error("Config file not found:" + this.metaConfig.getConfigFilePath(), e);
198. return new BooleanCommand(HttpStatus.InternalServerError, "Config file not found:" + this.metaConfig.getConfigFilePath(), request.getOpaque());
199. } catch (IOException e) {
200. log.error("IOException while stats config", e);
201. return new BooleanCommand(HttpStatus.InternalServerError, "Read config file error:" + e.getMessage(), request.getOpaque());
202. } catch (NotifyRemotingException e) {
203. log.error("NotifyRemotingException while stats config", e);
204. }
205. return null;
206. }

```
//Put请求的业务逻辑处理@Overridepublic void processPutCommand(final PutCommand request, final SessionContext sessionContext, final PutCallback cb) {		final String partitionString = this.metaConfig.getBrokerId() + "-" + request.getPartition();//统计计算		this.statsManager.statsPut(request.getTopic(), partitionString, 1);		this.statsManager.statsMessageSize(request.getTopic(), request.getData().length);		int partition = -1;		try {//如果对应存储的分区已经关闭，则拒绝该消息			if (this.metaConfig.isClosedPartition(request.getTopic(), request.getPartition())) {				log.warn("Can not put message to partition " + request.getPartition() + " for topic=" + request.getTopic() + ",it was closed");				if (cb != null) {					cb.putComplete(new BooleanCommand(HttpStatus.Forbidden, this.genErrorMessage(request.getTopic(), request.getPartition()) + "Detail:partition[" + partitionString + "] has been closed", request.getOpaque()));				}				return;			}			partition = this.getPartition(request);//获取对应Topic分区的MessageStore实例			final MessageStore store = this.storeManager.getOrCreateMessageStore(request.getTopic(), partition);			// 如果是动态添加的topic，需要注册到zk//就到目前为止，我着实没想明白下面这句代码的用途是什么？ //如果topic没有在该Broker的配置中配置，在MessageStoreManager中的isLegalTopic()方法中检查就通不过而抛出异常，那么下面这句代码怎么样都不会被执行，而Client要向Broker发送消息，一定要先发布topic，保证topic在zk发布； 			this.brokerZooKeeper.registerTopicInZk(request.getTopic(), false);			// 设置唯一id			final long messageId = this.idWorker.nextId();			//存储消息，之前的文章介绍过Broker的存储使用回调的方式，易于异步的实现，代码简单不分析store.append(messageId, request, new StoreAppendCallback(partition, partitionString, request, messageId, cb));		} catch (final Exception e) {//发生异常，统计计算回滚			this.statsManager.statsPutFailed(request.getTopic(), partitionString, 1);			log.error("Put message failed", e);			if (cb != null) {//返回结果				cb.putComplete(new BooleanCommand(HttpStatus.InternalServerError, this.genErrorMessage(request.getTopic(), partition) + "Detail:" + e.getMessage(), request.getOpaque()));			}		}	}@Override// GET请求的业务逻辑处理public ResponseCommand processGetCommand(final GetCommand request, final SessionContext ctx) {//默认为zeroCopy		return this.processGetCommand(request, ctx, true);	}	@Override	public ResponseCommand processGetCommand(final GetCommand request, final SessionContext ctx, final boolean zeroCopy) {//获取查询信息		final String group = request.getGroup();		final String topic = request.getTopic();//统计计数（请求数统计）		this.statsManager.statsGet(topic, group, 1);		// 如果分区被关闭,禁止读数据 --wuhua		if (this.metaConfig.isClosedPartition(topic, request.getPartition())) {			log.warn("can not get message for topic=" + topic + " from partition " + request.getPartition() + ",it closed,");			return new BooleanCommand(HttpStatus.Forbidden, "Partition[" + this.metaConfig.getBrokerId() + "-" + request.getPartition() + "] has been closed", request.getOpaque());		}//获取topic对应分区的MessageStore实例，如果实例不存在，则返回NotFound		final MessageStore store = this.storeManager.getMessageStore(topic, request.getPartition());		if (store == null) {//统计计数			this.statsManager.statsGetMiss(topic, group, 1);			return new BooleanCommand(HttpStatus.NotFound, "The topic `" + topic + "` in partition `" + request.getPartition() + "` is not exists", request.getOpaque());		}//如果请求的起始位置<0，判定该请求无效		if (request.getMaxSize() <= 0) {			return new BooleanCommand(HttpStatus.BadRequest, "Bad request,invalid max size:" + request.getMaxSize(), request.getOpaque());		}		try {//读取由request.getOffset()开始的消息集合			final MessageSet set = store.slice(request.getOffset(), Math.min(this.metaConfig.getMaxTransferSize(), request.getMaxSize()));//如果当前消息集不为空			if (set != null) {//判断是否zeroCopy，如果是zeroCopy，则直接写；如果不是，则将消息集包装成DataCommand，这也就是前面为什么说DataCommand要实现encode()方法的缘故				if (zeroCopy) {					set.write(request, ctx);					return null;				} else {					// refer to the code of line 440 in MessageStore					// create two copies of byte array including the byteBuffer					// and new bytes					// this may not a good use case of Buffer					final ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(this.metaConfig.getMaxTransferSize(), request.getMaxSize()));					set.read(byteBuffer);					byteBuffer.flip();					final byte[] bytes = new byte[byteBuffer.remaining()];					byteBuffer.get(bytes);					return new DataCommand(bytes, request.getOpaque());				}			} else {//如果为空消息集，则认为请求无效//统计计数				this.statsManager.statsGetMiss(topic, group, 1);				this.statsManager.statsGetFailed(topic, group, 1);				// 当请求的偏移量大于实际最大值时,返回给客户端实际最大的偏移量.				final long maxOffset = store.getMaxOffset();				final long requestOffset = request.getOffset();				if (requestOffset > maxOffset && (this.metaConfig.isUpdateConsumerOffsets() || requestOffset == Long.MAX_VALUE)) {					log.info("offset[" + requestOffset + "] is exceeded,tell the client real max offset: " + maxOffset + ",topic=" + topic + ",group=" + group);					this.statsManager.statsOffset(topic, group, 1);					return new BooleanCommand(HttpStatus.Moved, String.valueOf(maxOffset), request.getOpaque());				} else {					return new BooleanCommand(HttpStatus.NotFound, "Could not find message at position " + requestOffset, request.getOpaque());				}			}		} catch (final ArrayIndexOutOfBoundsException e) {			log.error("Could not get message from position " + request.getOffset() + ",it is out of bounds,topic=" + topic);			// 告知最近可用的offset			this.statsManager.statsGetMiss(topic, group, 1);			this.statsManager.statsGetFailed(topic, group, 1);			final long validOffset = store.getNearestOffset(request.getOffset());			this.statsManager.statsOffset(topic, group, 1);			return new BooleanCommand(HttpStatus.Moved, String.valueOf(validOffset), request.getOpaque());		} catch (final Throwable e) {			log.error("Could not get message from position " + request.getOffset(), e);			this.statsManager.statsGetFailed(topic, group, 1);			return new BooleanCommand(HttpStatus.InternalServerError, this.genErrorMessage(request.getTopic(), request.getPartition()) + "Detail:" + e.getMessage(), request.getOpaque());		}	}//查询最近可用offset请求的业务逻辑处理@Override	public ResponseCommand processOffsetCommand(final OffsetCommand request, final SessionContext ctx) {//统计计数		this.statsManager.statsOffset(request.getTopic(), request.getGroup(), 1);//获取topic对应分区的MessageStore实例		final MessageStore store = this.storeManager.getMessageStore(request.getTopic(), request.getPartition());//如果为空，则返回未找到		if (store == null) {			return new BooleanCommand(HttpStatus.NotFound, "The topic `" + request.getTopic() + "` in partition `" + request.getPartition() + "` is not exists", request.getOpaque());		}		//获取topic对应分区最近可用的offsetfinal long offset = store.getNearestOffset(request.getOffset());		return new BooleanCommand(HttpStatus.Success, String.valueOf(offset), request.getOpaque());	}//退出请求业务逻辑处理	@Override	public void processQuitCommand(final QuitCommand request, final SessionContext ctx) {		try {			if (ctx.getConnection() != null) {				//关闭与客户端的连接				ctx.getConnection().close(false);			}		} catch (final NotifyRemotingException e) {			// ignore		}	}//版本查询请求业务逻辑处理@Override	public ResponseCommand processVesionCommand(final VersionCommand request, final SessionContext ctx) {//返回当前Broker版本		return new BooleanCommand(HttpStatus.Success, BuildProperties.VERSION, request.getOpaque());	}//统计请求查询业务逻辑处理	@Override	public ResponseCommand processStatCommand(final StatsCommand request, final SessionContext ctx) {//判断类型，如果类型以config 开头，则传输整个配置文件		final String item = request.getItem();		if ("config".equals(item)) {			return this.processStatsConfig(request, ctx);		} else {//如果是获取统计结果，则从统计模块获取响应结果并返回给客户端			final String statsInfo = this.statsManager.getStatsInfo(item);			return new BooleanCommand(HttpStatus.Success, statsInfo, request.getOpaque());		}	}	//获取配置文件内容，使用zeroCopy将文件内容发送到客户端，构造的响应用BooleanCommand@SuppressWarnings("resource")	private ResponseCommand processStatsConfig(final StatsCommand request, final SessionContext ctx) {		try {			final FileChannel fc = new FileInputStream(this.metaConfig.getConfigFilePath()).getChannel();			// result code length opaque\r\n			IoBuffer buf = IoBuffer.allocate(11 + 3 + ByteUtils.stringSize(fc.size()) + ByteUtils.stringSize(request.getOpaque()));			ByteUtils.setArguments(buf, MetaEncodeCommand.RESULT_CMD, HttpStatus.Success, fc.size(), request.getOpaque());			buf.flip();			ctx.getConnection().transferFrom(buf, null, fc, 0, fc.size(), request.getOpaque(),					new SingleRequestCallBackListener() {						@Override						public void onResponse(ResponseCommand responseCommand, Connection conn) {							this.closeChannel();						}						@Override						public void onException(Exception e) {							this.closeChannel();						}						private void closeChannel() {							try {								fc.close();							} catch (IOException e) {								log.error("IOException while stats config", e);							}						}						@Override						public ThreadPoolExecutor getExecutor() {							return null;						}					}, 5000, TimeUnit.MILLISECONDS);		} catch (FileNotFoundException e) {			log.error("Config file not found:" + this.metaConfig.getConfigFilePath(), e);			return new BooleanCommand(HttpStatus.InternalServerError, "Config file not found:" + this.metaConfig.getConfigFilePath(), request.getOpaque());		} catch (IOException e) {			log.error("IOException while stats config", e);			return new BooleanCommand(HttpStatus.InternalServerError, "Read config file error:" + e.getMessage(), request.getOpaque());		} catch (NotifyRemotingException e) {			log.error("NotifyRemotingException while stats config", e);		}		return null;	}
```

如果不使用内容的事务，Broker已经完成了从网络接收数据—&gt;处理请求(存储消息/查询结果等)—&gt;返回结果的流程，Broker最基础的流程已经基本分析完毕。