rocketMQ学习笔记——nameServer
nameServer
nameServer是一个服务中心, 用于broker的注册, 然后consumer和producer通过连接namesrv获取broker的信息, namesrv是无状态的节点, 这意味着它不会有主从之分
以下是官方文档对namesrv的概念说明
名称服务充当路由消息的提供者。生产者或消费者能够通过名字服务查找各主题相应的Broker IP列表。多个Namesrv实例组成集群,但相互独立,没有信息交换。
namesrv的启动需要设置启动参数
-c /home/rocketmq/conf/namesrv.properties 设置配置文件
在配置文件中可以设置rocketmqHome, 它的作用会在后面namesrv源码中有所体现
public static void main(String[] args) {
main0(args);
}
public static NamesrvController main0(String[] args) {
try {
// 创建namesrv的控制器
NamesrvController controller = createNamesrvController(args);
// 启动控制器, 启动namesrv服务
start(controller);
String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
log.info(tip);
System.out.printf("%s%n", tip);
return controller;
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
main方法很简单, 他仅仅创建了一个nameSrv的控制器, 然后启动控制器而已
这里只给出重要的部分
public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
// 构建命令行选项nameServer地址和help
Options options = ServerUtil.buildCommandlineOptions(new Options());
// 如果options中是help则打印help信息然后退出
// 给options中添加c:{配置文件}和p:{打印配置信息}参数
commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
if (null == commandLine) {
System.exit(-1);
return null;
}
final NamesrvConfig namesrvConfig = new NamesrvConfig();
final NettyServerConfig nettyServerConfig = new NettyServerConfig();
// 设置了namesrv的端口信息
nettyServerConfig.setListenPort(9876);
if (commandLine.hasOption('c')) {
// 获取配置文件地址
String file = commandLine.getOptionValue('c');
if (file != null) {
// 创建输入流读取配置文件
InputStream in = new BufferedInputStream(new FileInputStream(file));
properties = new Properties();
properties.load(in);
// 通过反射设置对象参数
MixAll.properties2Object(properties, namesrvConfig);
MixAll.properties2Object(properties, nettyServerConfig);
namesrvConfig.setConfigStorePath(file);
System.out.printf("load config properties file OK, %s%n", file);
in.close();
}
}
MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
// rocketmqHome的值是从args中获取的, 启动时需要配置
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);
System.exit(-2);
}
final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);
// remember all configs to prevent discard
controller.getConfiguration().registerConfig(properties);
return controller;
}
controller的创建就是
- 设置rocketmq的版本
- 设置namesrv端口
- 读取预设的配置文件
接下去就是controller的启动
public static NamesrvController start(final NamesrvController controller) throws Exception {
if (null == controller) {
throw new IllegalArgumentException("NamesrvController is null");
}
// 做controller的初始化
boolean initResult = controller.initialize();
if (!initResult) {
controller.shutdown(