net.kut3.messaging.kafka.KafkaProducer Maven / Gradle / Ivy
/*
* Copyright 2019 Kut3Net.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kut3.messaging.kafka;
import java.util.Properties;
import org.apache.kafka.clients.producer.ProducerRecord;
/**
*
*/
public final class KafkaProducer {
private final ProducerBuilder builder;
private org.apache.kafka.clients.producer.KafkaProducer producer;
private KafkaProducer(ProducerBuilder builder) {
this.builder = builder;
this.initProducer();
}
/**
*
* @param key Key to produce
* @param value Value to produce
*/
public void produce(String key, String value) {
this.producer.send(new ProducerRecord<>(this.builder.topic,
key, value)
);
}
/**
*
*/
public void close() {
this.producer.close();
}
private void initProducer() {
Properties props = new Properties();
props.put("bootstrap.servers", this.builder.servers);
props.put("acks", "all");
props.put("delivery.timeout.ms", 31000);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
this.producer = new org.apache.kafka.clients.producer.KafkaProducer<>(props);
}
/**
*
* @return new {@link ProducerBuilder}
*/
public static ProducerBuilder newBuilder() {
return new ProducerBuilder();
}
/**
*
*/
public static final class ProducerBuilder {
private String servers;
private String topic;
private ProducerBuilder() {
}
/**
*
* @param servers Host port pairs separate by comma
* @return The current {@link ProcessBuilder} instance
*/
public ProducerBuilder servers(String servers) {
this.servers = servers;
return this;
}
/**
*
* @param topic Kafka topic to produce message
* @return The current {@link ProcessBuilder} instance
*/
public ProducerBuilder topic(String topic) {
this.topic = topic;
return this;
}
/**
*
* @return A new {@link KafkaProducer} instance
*/
public KafkaProducer build() {
return new KafkaProducer(this);
}
}
}