kafka consumer 配置 及 监听消息

@Configuration
@EnableKafka
public class KafkaConfiguration{
    
    @Value{"${spring.kafka.consumer.bootstrap-servers}"}
    private String consumerServer;
    @Value{"${spring.kafka.consumer.enable-auto-commit}"}
    private Boolean autoCommit;
    @Value{"${spring.kafka.consumer.auto-commit-interval}"}
    private Integer autoCommitInterval;
    @Value{"${spring.kafka.consumer.group-id}"}
    private String groupId;
    @Value{"${spring.kafka.consumer.max-poll-records}"}
    private Integer maxPollRecords;
    @Value{"${spring.kafka.consumer.auto-offset-reset}"}
    private String autoOffsetReset;
    @Value{"${spring.kafka.consumer.concurrency}"}
    private Integer concurrency;
    @Value{"${spring.kafka.consumer.session.timeout}"}
    private Integer sessionTimeOut;


    @Bean
    public Map consumerConfigs(){
        Map props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONNFIG,consumerServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG,grouId);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,autoOffsetReset);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,autoCommit);
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG,maxPollRecords);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG,sessionTimeOut);
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,autoCommitInterval);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class);           
      props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class);
        return props;
    }

    /**
     * 消费者批量工程
     */
    public KafkaListenerContainerFactory kafkaListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory factory = new
        ConcurrentKafkaListenerContainerFactory<>();

        factory.setConsumerFactory(new DefaultKafkaConsumerFactory)        
        (consumerConfigs()));

        factory.setBatchListener(true);
        factory.setConcurrency(concurrency);
        factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.Ack
        Mode.MANUAL);
        return factory;
    }
}

监听:

@Component
public class KafkaConsumer{
    

    @KafkaListener(topic="${spring.kafka.consumer.topic}"),containerFactory="kafkaListenerContainerFactory")
public void listen(List> records,Acknowledgment acklegment){
    
    for(ConsumerRecord datum : records){
        
        //此处你的业务逻辑 
        datum.value;
        
     }
    

    }
}

温馨提示:纯手打,小心有误;

你可能感兴趣的:(java)