Skip to content

Instantly share code, notes, and snippets.

@extantpedant
Created February 16, 2018 00:30
Show Gist options
  • Save extantpedant/ed34f3976571c032c416f4c6668a9b82 to your computer and use it in GitHub Desktop.
Save extantpedant/ed34f3976571c032c416f4c6668a9b82 to your computer and use it in GitHub Desktop.
little wrapper for embedded zookeeper server
package com.level3.tr.zookeeper
import org.apache.curator.test.TestingServer
import java.io.IOException
import com.typesafe.scalalogging.slf4j.LazyLogging
import java.io.File
/**
* Runs an in-memory, "embedded" instance of a ZooKeeper server.
*
* The ZooKeeper server instance is automatically started when you create a new instance of this class.
*
* based on io.confluent.examples.streams.zookeeper
*
* wraps https://curator.apache.org/apidocs/org/apache/curator/test/TestingServer.html
*/
@throws[Exception]
class ZooKeeperEmbedded extends LazyLogging {
logger.debug("Starting embedded ZooKeeper server...")
val server = new TestingServer()
logger.debug(s"Embedded ZooKeeper server at ${server.getConnectString} uses the temp directory at ${server.getTempDirectory}")
@throws[IOException]
def stop(): Unit = {
logger.debug(s"Shutting down embedded ZooKeeper server at ${server.getConnectString} ...")
server.close()
logger.debug(s"Shutdown of embedded ZooKeeper server at ${server.getConnectString} completed")
}
/**
* The ZooKeeper connection string aka `zookeeper.connect` in `hostnameOrIp:port` format.
* Example: `127.0.0.1:2181`.
*
* You can use this to e.g. tell Kafka brokers how to connect to this instance.
*/
@throws[IOException]
def connectString: String = server.getConnectString
/**
* The hostname of the ZooKeeper instance. Example: `127.0.0.1`
*/
def hostname: String = { // "server:1:2:3" -> "server:1:2"
connectString.substring(0, connectString.lastIndexOf(':'))
}
def port: Int = server.getPort()
def tempDir: File = server.getTempDirectory()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment