1.项目搭建
2.关键代码与配置
3.性能调优
注意,本项目基于spring boot 1,如果是spring boot 2有可能会报错.相应的包需要更新
1.项目搭建
kafka版本:kafka_2.11-1.0.0
jar包版本:1.1.7.REALEASE
<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>1.1.7.RELEASE</version> </dependency>
只需要在spring boot工程中加入改jar即可
2.关键代码与配置
实现生产者消费者需要实现几个关键bean
类 KafkaProducerConfig:
import org.apache.kafka.clients.producer.ProducerConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; 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; @Configuration @EnableKafka public class KafkaProducerConfig { @Bean("kafkaTemplate") public KafkaTemplate<String, String> kafkaTemplate() { KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<String, String>(producerFactory()); return kafkaTemplate; } @Value("${spring.kafka.bootstrap-servers}") private String kafkaServers; @Value("${spring.kafka.producer.retries}") private String retry; @Value("${spring.kafka.producer.batch-size}") private String batch; @Value("${spring.kafka.producer.buffer-memory}") private String mem; @Value("${spring.kafka.producer.key-serializer}") private String keySerializer; @Value("${spring.kafka.producer.value-serializer}") private String valueSerializer; public ProducerFactory<String, String> producerFactory() { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,kafkaServers); properties.put(ProducerConfig.RETRIES_CONFIG, retry); properties.put(ProducerConfig.BATCH_SIZE_CONFIG, batch); properties.put(ProducerConfig.LINGER_MS_CONFIG, 1); properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, mem); properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer); return new DefaultKafkaProducerFactory<String, String>(properties); } }
几个关键配置:
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG //kafka地址 ProducerConfig.BATCH_SIZE_CONFIG //批量发送配置,单位字节 当多个数据同时发往一个分区时,将被批量控制,减少对服务端的请求 ProducerConfig.BUFFER_MEMORY_CONFIG //生产者缓存,单位字节 生产者对发送数据的缓存总数
现在就构造出了kafkaTemplate对象,可以用他发送消息
kafkaTemplate.send(topic, 0, gson.toJson(Object));
send可以只传三个参数:topic,分区,数据
消费者代码和配置:
类 KafkaConsumerBatchConfig
package com.newland.dc.kafka.kafka; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.config.KafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.AbstractMessageListenerContainer; import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; import java.util.HashMap; import java.util.Map; @Configuration @EnableKafka public class KafkaConsumerBatchConfig { @Value("${spring.kafka.bootstrap-servers}") private String servers; @Value("${spring.kafka.consumer.enable-auto-commit}") private boolean auto; @Value("${spring.kafka.consumer.auto-commit-interval}") private int interval; @Value("${spring.kafka.consumer.group-id}") private String group; @Value("${spring.kafka.consumer.auto-offset-reset}") private String reset; @Value("${spring.kafka.consumer.key-deserializer}") private String keyDeserializer; @Value("${spring.kafka.consumer.value-deserializer}") private String valueDeserializer; @Value("${spring.kafka.consumer.max-poll-records:100}") private String maxPollRecords; @Value("${spring.kafka.consumer.max-poll-interval:1000000}") private String maxPollInterval; public ConsumerFactory<String, String> consumerFactory() { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);//注意这里修改为kafka的具体配置项目,我这里只是为了开发演示方便 properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, auto); properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, interval); properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer); properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer); properties.put(ConsumerConfig.GROUP_ID_CONFIG, group); properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, reset); properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPollInterval); return new DefaultKafkaConsumerFactory<String, String>(properties); } @Bean public KafkaListenerContainerFactory<?> batchFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(1); factory.setBatchListener(true);//设置为批量消费,每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.MANUAL_IMMEDIATE);//设置提交偏移量的方式 return factory; } }
关键配置:
ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG //由于此处批量我们用手动提交,所以该配置改为false ConsumerConfig.MAX_POLL_RECORDS_CONFIG //每次批量消费最大数 factory.setBatchListener(true); //注意把批量消费开启
消费者代码:对话题的每个分区监听,注意containerFactory配置
@Component public class MyListener { @Autowired private KafkaReceiverBatch kafkaReceiverBatch; private final Log log = LogFactory.getLogger(MyListener.class); @KafkaListener(id = "id0",containerFactory = "batchFactory", topicPartitions = { @TopicPartition(topic = "${consumer.log.topic:log.business}", partitions = { "0" }) }) public void listenPartition0(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) { log.info(LogProperty.LOGCONFIG_DEALID,"partition:0, size " + records.size()); kafkaReceiverBatch.batchConsumer(records,ack); a1 = printNum("0",a += records.size(),a1); } @KafkaListener(id = "id1",containerFactory = "batchFactory", topicPartitions = { @TopicPartition(topic = "${consumer.log.topic:log.business}", partitions = { "1" }) }) public void listenPartition1(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) { log.info(LogProperty.LOGCONFIG_DEALID,"partition:1, size " + records.size()); kafkaReceiverBatch.batchConsumer(records,ack); b1 = printNum("1",b += records.size(),b1); } @KafkaListener(id = "id2",containerFactory = "batchFactory", topicPartitions = { @TopicPartition(topic = "${consumer.log.topic:log.business}", partitions = { "2" }) }) public void listenPartition2(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) { log.info(LogProperty.LOGCONFIG_DEALID,"partition:2, size " + records.size()); kafkaReceiverBatch.batchConsumer(records,ack); c1 = printNum("2",c += records.size(),c1); } static Integer a = 0,b = 0,c = 0; static Integer a1 = 0,b1 = 0 ,c1 = 0 ; private Integer printNum(String threadTag, Integer num, Integer printTimes){ if( num/100000 > printTimes ){ System.out.println("partition:" + threadTag + ",consumer num:" + num); printTimes ++; } return printTimes; } }
消费逻辑也贴个例子:
protected void batchConsumer(List<ConsumerRecord<?, ?>> records, Acknowledgment ack){ for (ConsumerRecord<?, ?> record : records) { try { Optional<?> kafkaMessage = Optional.ofNullable(record.value()); if (kafkaMessage.isPresent()) { Object message = kafkaMessage.get(); AllLogBase allLogBase = gson.fromJson(message.toString(), AllLogBase.class); } } catch (Exception e) { e.printStackTrace(); continue; } } ack.acknowledge();//手动提交偏移量 }
3.性能调优
kafka生产和消费要注意几个关键点:
1.kafka生产者异步:
pool.execute(()->{kafkaTemplate.send(topic, 0, gson.toJson(Object));});
比如此处可以改为线程池
2.批量写入,可以更改生产者的批量发送值和缓存值,加大该值将大幅提升性能
3.消费者分区监听,并开启批量消费,提升性能