背景介绍
ZooKeeper可以以standalone
,伪分布式和分布式三种方式部署.standalone
模式下只有一台机器作为服务器,丧失了ZooKeeper高可用的特点.伪分布式是在一台电脑上使用不同端口启动多个ZooKeeper服务器.分布式是使用多个机器,每台机器上部署一个ZooKeeper服务器,即使有服务器宕机,只要少于半数,ZooKeeper集群依然可以正常对外提供服务.
ZooKeeper以standalone
模式启动只需启动对客户端提供服务的组件,无需启动集群内部通信组件,较为简单,因此先从standalone
模式开始介绍.
整体架构
Zookeeper整体架构如上图,其中包括ServerCnxnFactory
,SessionTracker
,RequestProcessor
,FileTxnSnapLog
等众多组件,这些组件都会在日后一一介绍.
启动流程概述
standalone
模式启动主要包括如下几个步骤:
- 配置文件解析
- 创建并启动历史文件清理器
- 初始化数据管理器
- 注册shutdownHandler
- 启动Admin server
- 创建并启动网络IO管理器
- 启动ZooKeeperServer
- 创建并启动secureCnxnFactory
- 创建并启动ContainerManager
源码如下:
protected void initializeAndRun(String[] args)
throws ConfigException, IOException, AdminServerException {
//1.解析配置文件
QuorumPeerConfig config = new QuorumPeerConfig();
if (args.length == 1) {
config.parse(args[0]);
}
// Start and schedule the the purge task
//2.创建并启动历史文件清理器(对事务日志和快照数据文件进行定时清理)
DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config
.getDataDir(), config.getDataLogDir(), config
.getSnapRetainCount(), config.getPurgeInterval());
purgeMgr.start();
if (args.length == 1 && config.isDistributed()) {
//集群启动
runFromConfig(config);
} else {
//单机启动
LOG.warn("Either no config or no quorum defined in config, running "
+ " in standalone mode");
// there is only server in the quorum -- run as standalone
ZooKeeperServerMain.main(args);
}
}
/**
* Run from a ServerConfig.
*
* @param config ServerConfig to use.
* @throws IOException
* @throws AdminServerException
*/
public void runFromConfig(ServerConfig config)
throws IOException, AdminServerException {
LOG.info("Starting server");
FileTxnSnapLog txnLog = null;
try {
//3.创建ZooKeeper数据管理器
txnLog = new FileTxnSnapLog(config.dataLogDir, config.dataDir);
final ZooKeeperServer zkServer = new ZooKeeperServer(txnLog,
config.tickTime, config.minSessionTimeout, config.maxSessionTimeout, null);
txnLog.setServerStats(zkServer.serverStats());
//4.注册shutdownHandler,在ZooKeeperServer的状态变化时调用shutdownHandler的handle()
final CountDownLatch shutdownLatch = new CountDownLatch(1);
zkServer.registerServerShutdownHandler(
new ZooKeeperServerShutdownHandler(shutdow