kafka.entity.changelog.topic.TopicCommander Maven / Gradle / Ivy
package kafka.entity.changelog.topic;
import java.io.IOException;
import java.util.Properties;
import kafka.entity.changelog.schema.Topic;
import kafka.entity.changelog.serde.CommandSerde;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import static kafka.entity.changelog.schema.Topic.Command;
import static kafka.entity.changelog.schema.Topic.CreateTopic;
public class TopicCommander {
final TopicCommandRepository commandRepository;
final KafkaProducer commandProducer;
TopicCommander(Builder builder) {
this.commandProducer = new KafkaProducer<>(
builder.producerConfig,
new StringSerializer(),
new CommandSerde().serializer());
this.commandRepository = TopicCommandRepository.create(
commandProducer,
builder.commandTopicName);
}
public void createTopic(String topicName, int partitions, short replicationFactor,
String username, String source) throws IOException {
CreateTopic createTopic = CreateTopic.newBuilder()
.setName(topicName)
.setPartitions(partitions)
.setReplicationFactor(replicationFactor)
.build();
Command command = Command.newBuilder()
.setUsername(username)
.setSource(source)
.setTimestamp(System.currentTimeMillis())
.setCreateTopic(createTopic)
.build();
commandRepository.put(command);
commandRepository.flush();
}
public static class Builder {
String bootstrapServers = "localhost:19092";
String commandTopicName = "_changelog_topic_command";
Properties producerConfig = new Properties();
Builder() {
this.producerConfig.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
}
public TopicCommander build() {
return new TopicCommander(this);
}
}
public static Builder newBuilder() {
return new Builder();
}
}