1. 程式人生 > 實用技巧 >java向kafka傳送訊息

java向kafka傳送訊息

pom.xml:

<dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
            <version>1.0.6.RELEASE</version>
        </dependency>

kafkaTest:


import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;


public class KafkaTest {

public static void main(String[] args) {
KafkaTemplate<String, String> kafkaTemplate = kafkaTemplate();
for (int i = 0; i < 100; i++) {
kafkaTemplate.send("test-david", "key", "this is test msg");
}
}

public static KafkaTemplate<String, String> kafkaTemplate() {
Map<String, Object> configs = new HashMap<>();
//kafka伺服器地址
configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hdp01.ultiwill.com:6667,hdp02.ultiwill.com:6667");
//失敗允許重試的次數
configs.put(ProducerConfig.RETRIES_CONFIG, 0);
//每個批次傳送多大的資料
configs.put(ProducerConfig.BATCH_SIZE_CONFIG, 4096);
//定時傳送, 達到1ms傳送
configs.put(ProducerConfig.LINGER_MS_CONFIG, 1);
//快取的大小
configs.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 40960);
configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, RoundRobinPartitioner.class);
configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

ProducerFactory<String, String> producerFactory = new DefaultKafkaProducerFactory<>(configs);

return new KafkaTemplate<String, String>(producerFactory);
}
}