一、原声kafka一般操作如下:
package com.zhanglijie.entity;
import cn.hutool.core.util.StrUtil;
import com.zhanglijie.entity.config.QueueConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Slf4j
@Data
public class KafkaManager {
private static final Integer sessionTimeout = 30000;
private static final Integer pollMaxRecord =1;
private static final String OFFSET_POLICY = "earliest";
private static final Integer heatbeatInterval = 5000;
private static final Integer maxPollInterval = 90000;
private static final String SEP = "_";
private static Map consumerMap = new HashMap<>();
private static Map producerMap = new HashMap<>();
public static Consumer getConsumer(QueueConfigMessage config){
String key = getConsumerKey(config);
//直接从消费者连接池获得一个
if(consumerMap.containsKey(key) && consumerMap.get(key) != null){
return consumerMap.get(key);
}else{
Properties properties = generateConfig(config);
Consumer consumer = new KafkaConsumer<>(properties);
consumer.subscribe(Arrays.asList(config.getQueueName()));
consumerMap.put(key,consumer);
log.info("create a new consumer success,the queue-server is {},the topic is {}",config.getQueueServer(),config.getQueueName());
return consumer;
}
}
private static String getConsumerKey(QueueConfigMessage config){
String queueName = config.getQueueName();
String consumerGroup = config.getConsumerGroup();
return (queueName+SEP+consumerGroup+SEP+Thread.currentThread().getName());
}
private static Properties generateConfig(QueueConfigMessage config){
Properties props = new Properties();
//kafka集群地址
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getQueueServer());
//消费组
props.put(ConsumerConfig.GROUP_ID_CONFIG, config.getConsumerGroup());
//自动提交偏移量
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
//最大会话时间,如果超过就会被踢出此消费组
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG,sessionTimeout);
//拉取间隔最大限制
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, pollMaxRecord);
//key的反序列化方式
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
//value的反序列化方式
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
//从最新的偏移量开始消费
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,OFFSET_POLICY);
props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG,heatbeatInterval);
props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG,maxPollInterval);
//中台权限设置(这是我自己公司需要的权限,开源kafka是不需要这个if操作的)
if(!StrUtil.isEmpty(config.getQueueAuth())){
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG,"SASL_PLAINTEXT");
props.put(SaslConfigs.SASL_MECHANISM,"SCRAM-SHA-256");
props.put("sasl.jaas.config",config.getQueueAuth());
}
return props;
}
public static Consumer removeAndReGetConsumer(QueueConfigMessage config){
String key = getConsumerKey(config);
removeConsumer(key);
Consumer consumer = getConsumer(config);
log.info("old consumer has been removed from cache,the key is {}",key);
return consumer;
}
public static void removeConsumer(String key){
consumerMap.remove(key);
log.info("this consumer has been cleaned from cache ,the key is {}",key);
}
public static Producer getProducer(QueueConfigMessage toQueueConfigMessage){
String key = getProducerKey(toQueueConfigMessage);
if(producerMap.containsKey(key)){
return producerMap.get(key);
}
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, toQueueConfigMessage.getQueueServer());
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.ACKS_CONFIG,"all");
//如果带了auth信息 一般指的是中台kafka
if(!StrUtil.isEmpty(toQueueConfigMessage.getQueueAuth())){
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
props.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
props.put("sasl.jaas.config", toQueueConfigMessage.getQueueAuth());
}
Producer producer = new KafkaProducer<>(props);
log.info("create a new producer sucess,the queue-server is {}",toQueueConfigMessage.getQueueServer());
producerMap.put(key,producer);
return producer;
}
private static String getProducerKey(QueueConfigMessage toQueueConfigMessage){
String queueServer = toQueueConfigMessage.getQueueServer();
String auth = toQueueConfigMessage.getQueueAuth();
return (queueServer+SEP+auth+SEP+Thread.currentThread().getName());
}
public static Producer removeAndReGetProducer(QueueConfigMessage toQueueConfigMessage){
String key= getProducerKey(toQueueConfigMessage);
removeProducer(key);
log.info("old producer has been removed from cache,the key is {}",key);
return getProducer(toQueueConfigMessage);
}
public static void removeProducer(String key){
producerMap.remove(key);
log.info("this producer has been cleaned from cache, the key is {}",key);
}
}
说明:之所以使用一个Manager来管理这些consumer和producer是因为
1.如果不使用manager来管理consumer,每次消费都创建一个去连接消费者协调器 性能较低,因为链接协调器需要类似的三次握手操作,使用完了就会被消费者协调器抛弃,而是用manager来管理就可以通过创建几个消费者放到内存池中常驻,常驻期间不会被消费者协调器抛弃,类似于数据库连接池一样的道理
2.有可能一个consumer在消费时候由于网络问题或者消费处理时间大于”heartbeat.interval.ms“而被消费者协调器抛弃这个消费者,那么下次使用这个消费者就是无效的,因此需要一个manager来主动更新consumer。
注意:使用原声的kafka客户端操作kafka,操作复杂,需要自己创建个manager来维护这些生产者和消费者,既然维护复杂为何不交给spring来维护呢? 下面就主要介绍kafka接入spring的两种方式,一种方式使用spring-kafka默认的配置文件(自定义有限,灵活度不高,容器不能兼容多个生产者或者消费者配置或者多个ProductTemplate),一种自己覆盖spring-kafka的默认Listener/ProductTemplate自定义程度高且灵活
方式一、使用spring-kafka的默认配置文件完成生产者和消费者
配置文件如下
spring.application.name=springboot-kafka-02 server.port=8080 # ⽤于建⽴初始连接的broker地址 spring.kafka.bootstrap-servers=node1:9092 # producer⽤到的key和value的序列化类 spring.kafka.producer.keyserializer= org.apache.kafka.common.serialization.IntegerSerializer spring.kafka.producer.valueserializer= org.apache.kafka.common.serialization.StringSerializer # 默认的批处理记录数 spring.kafka.producer.batch-size=16384 # 32MB的总发送缓存 spring.kafka.producer.buffer-memory=33554432 # consumer⽤到的key和value的反序列化类 spring.kafka.consumer.keydeserializer= org.apache.kafka.common.serialization.IntegerDeserializer spring.kafka.consumer.valuedeserializer= org.apache.kafka.common.serialization.StringDeserializer # consumer的消费组id spring.kafka.consumer.group-id=spring-kafka-02-consumer # 是否⾃动提交消费者偏移量 spring.kafka.consumer.enable-auto-commit=true # 每隔100ms向broker提交⼀次偏移量 spring.kafka.consumer.auto-commit-interval=100 # 如果该消费者的偏移量不存在,则⾃动设置为最早的偏移量 spring.kafka.consumer.auto-offset-reset=earliest
使用如下:
消费时候:
生产时候:
方式二、不使用spring-kafka的默认配置文件完成生产者和消费者
- 使用自定义配置文件(随意配置,也可以使用别人已经配置过的配置做个增量覆盖):
配置如下:
mykafka: bootstrapServers: localhost:9092 groupId: qws #后台的心跳线程必须在30秒之内提交心跳,否则会reBalance sessionTimeOut: 30000 autoOffsetReset: earliest #取消自动提交,即便如此 spring会帮助我们自动提交 enableAutoCommit: false #自动提交间隔 autoCommitInterval: 1000 #拉取的最小字节 fetchMinSize: 1 #拉去最小字节的最大等待时间 fetchMaxWait: 500 maxPollRecords: 50 #300秒的提交间隔,如果程序大于300秒提交,会报错 maxPollInterval: 300000 #心跳间隔 heartbeatInterval: 10000 keyDeserializer: org.apache.kafka.common.serialization.StringDeserializer valueDeserializer: org.apache.kafka.common.serialization.StringDeserializer
2.给个domain映射下自定义的配置
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
//指定配置文件的前缀
@ConfigurationProperties(prefix = "mykafka")
@Data
public class KafkaProperties {
private String groupId;
private String sessionTimeOut;
private String bootstrapServers;
private String autoOffsetReset;
private boolean enableAutoCommit;
private String autoCommitInterval;
private String fetchMinSize;
private String fetchMaxWait;
private String maxPollRecords;
private String maxPollInterval;
private String heartbeatInterval;
private String keyDeserializer;
private String valueDeserializer;
}
3.生产者:
import cn.hutool.core.util.StrUtil;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import java.util.Properties;
@Configuration
public class MyKafkaProducerConfig{
@Autowired
private KafkaProperties properties;
private String ssalConfig = "****xxx****";
@Bean
public KafkaTemplate myKafkaProductTemplate(){
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServers());
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.ACKS_CONFIG,"all");
//如果带了auth信息 一般指的是中台kafka(我们公司需要鉴权,如果是一般kafka调过此if)
if(!StrUtil.isEmpty(ssalConfig)){
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
props.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
props.put("sasl.jaas.config", ssalConfig);
}
return new KafkaTemplate(new DefaultKafkaProducerFactory(props));
}
}
4.消费者
@Configuration
@EnableConfigurationProperties(KafkaProperties.class)
@Slf4j
public class KafkaConsumerConfig {
@Autowired
KafkaProperties kafkaListenerProperties;
@Bean("mycontainer1")
public KafkaListenerContainerFactory> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
// 并发数 多个微服务实例会均分
// factory.setConcurrency(1);
// factory.setBatchListener(true);
ContainerProperties containerProperties = factory.getContainerProperties();
// 是否设置手动提交
containerProperties.setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
return factory;
}
@Bean("mycontainer2")
public ConcurrentKafkaListenerContainerFactory
使用时候:
消费使用案例:
@Slf4j
@Component
public class MyListener {
@KafkaListener(topics = "pkafka", groupId = "#flow.kafka.group.id",concurrency = "1",containerFactory = "kafkaListenerContainerFactory")
public void listenPartition0(List> records) throws InterruptedException {
log.info("Id0 Listener, Thread ID: " + Thread.currentThread().getId());
log.info("Id0 records size " + records.size());
// Thread.sleep(500000L);
for (ConsumerRecord, ?> record : records) {
Optional> kafkaMessage = Optional.ofNullable(record.value());
log.info("Received: " + record);
if (kafkaMessage.isPresent()) {
Object message = record.value();
log.info("p0 Received message={}", message);
}
}
}
}
生产使用案例:
@Slf4j
@Component
public class MyListener {
@Autowired
private KafkaTemplate myKafkaProductTemplate;
public void send(String msg){
myKafkaProductTemplate.send(new ProducerRecord());
}
}



