application.properties:
# Kafka
spring.kafka.bootstrap-servers=kafka1:9092,kafka2:9092,kafka3:9092
spring.kafka.producer.batch-size=10
spring.kafka.producer.buffer-memory=33554432
# Id to pass to the server when making requests; used for server-side logging.
spring.kafka.producer.client-id=s1
# Compression type for all data generated by the producer.
#spring.kafka.producer.compression-type=
# Serializer class for keys.
#spring.kafka.producer.key-serializer=
# When greater than zero, enables retrying of failed sends.
spring.kafka.producer.retries=3
使用KafkaTemplate发送消息:
package com.pasenger.kafka.producer.services; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * Kafka生产者 * Created by Pasenger on 2017/3/16. */ @Service @Setter @Getter @Slf4j public class KafkaProducerService { @Autowired private KafkaTemplate<Integer, String> kafkaTemplate; /** * 发送Kafka消息 * * @param topic kafka topic * @param partition kafka partition * @param message message */ @Async public void send(String topic, int partition, String message) { kafkaTemplate.send(topic, partition, message); kafkaTemplate.flush(); } }