2, Routing center NameServer of RockerMQ

Posted by sup on Sun, 24 Oct 2021 20:59:41 +0200

Routing center NameServer

  • What data is stored in the routing center?
  • How to avoid a single point of failure of nameserver?
  • How is it different from eukera and zookeeper?

1, NamesServer architecture design

  • How do producers know which server to send messages to in a multi broker server?
  • When a server goes down, how can producers perceive it without restarting the service?
  1. When the broker starts, it registers with all nameserver servers
  2. When the producer sends a message, it obtains the list of Broker servers from the nameserver and selects a server from the list according to the load balancing algorithm
  3. ameserver maintains a long connection with the broker. It is detected every 30s. If the broker is found to be down, it is removed from the routing list without notifying the message producer
  4. After the producer fails to send a message to the down server, re obtain the routing list and select one to continue sending

2, NameServer startup process

NameServer start org/apache/rocketmq/namesrv/NamesrvStartup.java

  1. First, to parse the configuration file, you need to fill in the NameServerConfig NettyServerConfig attribute value
public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
        System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));

        Options options = ServerUtil.buildCommandlineOptions(new Options());
        commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
        if (null == commandLine) {
            return null;

        final NamesrvConfig namesrvConfig = new NamesrvConfig();
        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
        if (commandLine.hasOption('c')) {
            String file = commandLine.getOptionValue('c');
            if (file != null) {
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                properties = new Properties();
                MixAll.properties2Object(properties, namesrvConfig);
                MixAll.properties2Object(properties, nettyServerConfig);


                System.out.printf("load config properties file OK, %s%n", file);

        if (commandLine.hasOption('p')) {
            InternalLogger console = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_NAME);
            MixAll.printObjectProperties(console, namesrvConfig);
            MixAll.printObjectProperties(console, nettyServerConfig);

        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);

        if (null == namesrvConfig.getRocketmqHome()) {
            System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);

        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");

        log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);

        MixAll.printObjectProperties(log, namesrvConfig);
        MixAll.printObjectProperties(log, nettyServerConfig);

        final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);

        // remember all configs to prevent discard

        return controller;
  1. Create a NamesrvController instance according to the startup properties, and initialize the instance NameServerController instance as the NameServer core controller

  2. Load kv configuration and start two scheduled tasks, which are called heartbeat detection in mq

  • Scheduled task I: NameServer scans brokers every Os to remove inactive brokers

  • Scheduled task 2: names rver prints KV configuration every 10 minutes

public boolean initialize() {


        this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);

        this.remotingExecutor =
            Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));


        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

            public void run() {
        }, 5, 10, TimeUnit.SECONDS);

        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

            public void run() {
        }, 1, 10, TimeUnit.MINUTES);

        if (TlsSystemConfig.tlsMode != TlsMode.DISABLED) {
            // Register a listener to reload SslContext
            try {
                fileWatchService = new FileWatchService(
                    new String[] {
                    new FileWatchService.Listener() {
                        boolean certChanged, keyChanged = false;
                        public void onChanged(String path) {
                            if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) {
                                log.info("The trust certificate changed, reload the ssl context");
                            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;
                        private void reloadServerSslContext() {
                            ((NettyRemotingServer) remotingServer).loadSslContext();
            } catch (Exception e) {
                log.warn("FileWatchService created error, can't load the certificate dynamically");

        return true;

  1. Register the JVM hook function and start the server to monitor the network requests of brokers and message producers
public static NamesrvController start(final NamesrvController controller) throws Exception {

        if (null == controller) {
            throw new IllegalArgumentException("NamesrvController is null");

        boolean initResult = controller.initialize();
        if (!initResult) {

        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
            public Void call() throws Exception {
                return null;


        return controller;

If a thread pool is used in the code, an elegant way to stop is to register the JVM hook function. Before closing the JVM process, close the thread pool to release resources in time

3, nameserver routing registration and fault deletion mechanism

1. Routing meta information

2. Route registration

3. Route deletion

4. Route discovery

Topics: RocketMQ MQ