/** * Create a new server instance. * * @param zookeeperConnection the supplier of the Zookeeper connection string; may not be null * @param brokerId the unique broker ID * @param port the desired port */ public KafkaServer(Supplier<String> zookeeperConnection, int brokerId, int port) { if (zookeeperConnection == null) throw new IllegalArgumentException("The Zookeeper connection string supplier may not be null"); this.zkConnection = zookeeperConnection; this.brokerId = brokerId; this.config = new Properties(); setPort(port); populateDefaultConfiguration(this.config); }
/** * Set the port numbers for Zookeeper and the Kafka brokers. * * @param zkPort the port number that Zookeeper should use; may be -1 if an available port should be discovered * @param firstKafkaPort the port number for the first Kafka broker (additional brokers will use subsequent port numbers); * may be -1 if available ports should be discovered * @return this instance to allow chaining methods; never null * @throws IllegalStateException if the cluster is running */ public KafkaCluster withPorts(int zkPort, int firstKafkaPort) { if (running) throw new IllegalStateException("Unable to add a broker when the cluster is already running"); this.zkServer.setPort(zkPort); this.startingKafkaPort = firstKafkaPort; if (this.startingKafkaPort >= 0) { this.nextKafkaPort.set(this.startingKafkaPort); kafkaServers.values().forEach(kafka -> kafka.setPort((int) this.nextKafkaPort.getAndIncrement())); } return this; }
/** * Add a number of new Kafka broker to the cluster. The broker IDs will be generated. * * @param count the number of new brokers to add * @return this instance to allow chaining methods; never null * @throws IllegalStateException if the cluster is running */ public KafkaCluster addBrokers(int count) { if (running) throw new IllegalStateException("Unable to add a broker when the cluster is already running"); AtomicLong added = new AtomicLong(); while (added.intValue() < count) { kafkaServers.computeIfAbsent(Integer.valueOf(added.intValue() + 1), id -> { added.incrementAndGet(); KafkaServer server = new KafkaServer(zkServer::getConnection, id); if (dataDir != null) server.setStateDirectory(dataDir); if (kafkaConfig != null) server.setProperties(kafkaConfig); if (startingKafkaPort >= 0) server.setPort((int) this.nextKafkaPort.getAndIncrement()); return server; }); } return this; }