是否可以在进程中启动 Zookeeper 服务器实例,例如用于单元测试?
2022-09-01 00:45:33
						调用 org.apache.zookeeper.server.quorum.QuorumPeerMain.main() 不起作用。
调用 org.apache.zookeeper.server.quorum.QuorumPeerMain.main() 不起作用。
Netfix开源了Curator一个框架,使Zookeeper的使用更加方便。它具有内置测试服务器类。只需将此测试依赖项添加到项目描述符中,无论是 maven、gradle 还是其他:
org.apache.curator:curator-framework:4.0.1
org.apache.curator:curator-test:4.0.1
以下是测试要点。
TestingServer zkTestServer;
CuratorFramework cli;
@Before
public void startZookeeper() throws Exception {
    zkTestServer = new TestingServer(2181);
    cli = CuratorFrameworkFactory.newClient(zkTestServer.getConnectString(), new RetryOneTime(2000));
    cli.start();
}
@After
public void stopZookeeper() throws IOException {
    cli.close();
    zkTestServer.stop();
}
创建任何测试数据都非常容易(需要依赖关系)。clicurator-framework
cli.create()
   .creatingParentsIfNeeded()
   .forPath("/a1", "testvalue".getBytes("UTF-8"));
						要开始,你必须执行类。ZooKeeperZooKeeperServerMain
可以使用以下代码在嵌入式模式下启动。ZooKeeper
Properties startupProperties = ...
QuorumPeerConfig quorumConfiguration = new QuorumPeerConfig();
try {
    quorumConfiguration.parseProperties(startupProperties);
} catch(Exception e) {
    throw new RuntimeException(e);
}
zooKeeperServer = new ZooKeeperServerMain();
final ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumConfiguration);
new Thread() {
    public void run() {
        try {
            zooKeeperServer.runFromConfig(configuration);
        } catch (IOException e) {
            log.error("ZooKeeper Failed", e);
        }
    }
}.start();