是否可以在进程中启动zookeeper服务器实例,比如单元测试?

mar*_*hon 44 java unit-testing apache-zookeeper

调用org.apache.zookeeper.server.quorum.QuorumPeerMain.main()不起作用.

ger*_*tas 60

Netfix opensourced 策展人使用Zookeeper的框架更加方便.它内置了测试服务器类.只需将此测试依赖项添加到您的项目描述符,无论是maven,gradle还是:

org.apache.curator:curator-framework:4.0.1
org.apache.curator:curator-test:4.0.1
Run Code Online (Sandbox Code Playgroud)

以下是测试要点.

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();
}
Run Code Online (Sandbox Code Playgroud)

随着cli创建任何测试数据是很容易的(需要curator-framework依赖).

cli.create()
   .creatingParentsIfNeeded()
   .forPath("/a1", "testvalue".getBytes("UTF-8"));
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,如果没有使用Curator 2.10.0版的cli.start(),它就无法工作 (2认同)

Mai*_*kov 45

要开始ZooKeeper你必须执行ZooKeeperServerMain课程.

您可以使用以下代码以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();
Run Code Online (Sandbox Code Playgroud)

  • 这是单元测试的方法.使用QuorumPeerMain仅适用于Multi Server(Clustered)Zookeeper. (4认同)
  • 这是一个比接受的答案更清晰的解决方案. (2认同)

小智 12

你可以使用这样的东西.

int clientPort = 21818; // none-standard
int numConnections = 5000;
int tickTime = 2000;
String dataDirectory = System.getProperty("java.io.tmpdir");

File dir = new File(dataDirectory, "zookeeper").getAbsoluteFile();

ZooKeeperServer server = new ZooKeeperServer(dir, dir, tickTime);
NIOServerCnxn.Factory standaloneServerFactory = new NIOServerCnxn.Factory(new InetSocketAddress(clientPort), numConnections);

standaloneServerFactory.startup(server); // start the server.
Run Code Online (Sandbox Code Playgroud)

并关闭它只是打电话 standaloneServerFactory.shutdown()