RocketMQ高可用设计之主从复制和读写分离

440 阅读3分钟

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金

27RocketMQ高可用设计之主从复制和读写分离

主从复制

RocketMQ为了提高消费的高可用性,避免Broker发生单点故障引起Broker上的消息无法及时消费,同时避免单个机器上硬盘坏损出现消费数据丢失。

RocketMQ采用Broker数据主从复制机制,当消息发送到Master服务器后会将消息同步到Slave服务器,如果Master服务器宕机,消息消费者还可以继续从Slave拉取消息。

消息从Master服务器复制到Slave服务器上,有两种复制方式:同步复制SYNC_MASTER和异步复制ASYNC_MASTER。

通过配置文件conf/broker.conf文件配置:

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

brokerClusterName = DefaultCluster
brokerName = broker-a
brokerId = 0
deleteWhen = 04
fileReservedTime = 48
brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUSH

对brokerRole参数进行设置。

同步复制:Master和Slave都写成功后才返回客户端写成功的状态。

  • 优点:Master服务器出现故障,Slave服务器上有全部数据的备份,很容易恢复到Master服务器。
  • 缺点:由于多了一个同步等待的步骤,增加数据写入延迟,降低系统吞吐量。

异步复制:仅Master服务器写成功即可返回给客户端写成功的状态。

  • 优点:没有同步等待的步骤,低延迟,高吞吐。
  • 缺点:如果Master服务器出现故障,有些数据可能未写入Slave服务器,未同步的数据可能丢失

实际应用中,需要结合业务场景,合理设置刷盘方式和主从复制方式。不建议使用同步刷盘方式,因为它频繁触发写磁盘操作,性能下降很明显。**通常把Master和Slave设置为异步刷盘,同步复制,保证数据不丢失。**这样即使一台服务器出故障,仍然可以保证数据不丢失。

读写分离

读写分离机制是高性能、高可用架构中常见的设计,例如Mysql实现读写分离机制,Client只能从Master服务器写数据,可以从Master服务器和Slave服务器都读数据。

RocketMQ的Consumer在拉取消息时,Broker会判断Master服务器的消息堆积量来决定Consumer是否从Slave服务器拉取消息消费。默认一开始从Master服务器拉群消息,如果Master服务器的消息堆积超过物理内存40%,则会返回给Consumer的消息结果并告知Consumer,下次从其他Slave服务器上拉取消息。

这就是RocketMQ高可用设计之主从复制和读写分离,希望对你有帮助。 如果你觉得这篇文章还不错的话,欢迎给我留言点赞,奥利给。