Kafka + SpringBoot集成

学习贴:参考https://blog.csdn.net/qq_20865839/article/details/133948989

简单SpringBoot整合:

依赖:

bash 复制代码
		<dependency>
			<groupId>org.springframework.kafka</groupId>
			<artifactId>spring-kafka</artifactId>
		</dependency>

生产者

bash 复制代码
@RestController
public class kafkaProducer {
 
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
    
    @GetMapping("/kafka/normal/{message}")
    public void sendNormalMessage(@PathVariable("message") String message) {
        kafkaTemplate.send("sb_topic", message);
    }

消费者:

bash 复制代码
@Component
public class KafkaConsumer {
 
    //监听消费
    @KafkaListener(topics = {"sb_topic"})
    public void onNormalMessage(ConsumerRecord<String, Object> record) {
        System.out.println("简单消费:" + record.topic() + "-" + record.partition() + "=" +
                record.value());
    }

生产者

带回调的生产者

kafkaTemplate提供了一个回调方法addCallback,我们可以在回调方法中监控消息是否发送成功 或 失败时做补偿处理

bash 复制代码
    /**
     * 回调的第二种写法
     * @param message
     */
    @GetMapping("/kafka/callbackTwo/{message}")
    public void sendCallbackTwoMessage(@PathVariable("message") String message) {
        kafkaTemplate.send("sb_topic", message).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("发送消息失败2:"+throwable.getMessage());
            }
 
            @Override
            public void onSuccess(SendResult<String, Object> result) {
                System.out.println("发送消息成功2:" + result.getRecordMetadata().topic() + "-"
                        + result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
            }
        });
    }

监听器

Kafka提供了ProducerListener 监听器来异步监听生产者消息是否发送成功,我们可以自定义一个kafkaTemplate添加ProducerListener,当消息发送失败我们可以拿到消息进行重试或者把失败消息记录到数据库定时重试。

注意:

当我们发送一条消息,既会走 ListenableFutureCallback 回调,也会走ProducerListener回调。

bash 复制代码
@Configuration
public class KafkaConfig {
 
    @Autowired
    ProducerFactory producerFactory;
 
    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        KafkaTemplate<String, Object> kafkaTemplate = new KafkaTemplate<String, Object>(producerFactory);
        kafkaTemplate.setProducerListener(new ProducerListener<String, Object>() {
            @Override
            public void onSuccess(ProducerRecord<String, Object> producerRecord, RecordMetadata recordMetadata) {
                System.out.println("发送成功 " + producerRecord.toString());
            }
 
            @Override
            public void onSuccess(String topic, Integer partition, String key, Object value, RecordMetadata recordMetadata) {
                System.out.println("发送成功 topic = " + topic + " ; partion = " + partition + "; key = " + key + " ; value=" + value);
            }
 
            @Override
            public void onError(ProducerRecord<String, Object> producerRecord, Exception exception) {
                System.out.println("发送失败" + producerRecord.toString());
                System.out.println(exception.getMessage());
            }
 
            @Override
            public void onError(String topic, Integer partition, String key, Object value, Exception exception) {
                System.out.println("发送失败" + "topic = " + topic + " ; partion = " + partition + "; key = " + key + " ; value=" + value);
                System.out.println(exception.getMessage());
            }
        });
        return kafkaTemplate;
    }
}
相关推荐
IT_Octopus4 分钟前
Java GZip 压缩实践 +实践思考 +进一步压榨性能和存储方案思考:Protobuf+ GZip
java·spring boot
毕设源码-郭学长40 分钟前
【开题答辩全过程】以 高校教材大管家系统为例,包含答辩的问题和答案
java·spring boot
qq_12498707531 小时前
基于SpringBoot+vue的小黄蜂外卖平台(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·后端·mysql·毕业设计
i02081 小时前
Java 17 + Spring Boot 3.2.5 使用 Redis 实现“生产者–消费者”任务队列
java·spring boot·redis
5***b972 小时前
SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)
spring boot·tomcat·mybatis
卷到起飞的数分2 小时前
22.Maven高级——继承与聚合
服务器·spring boot
P***84392 小时前
idea创建springBoot的五种方式
java·spring boot·intellij-idea
Q_Q19632884753 小时前
python+django/flask+vue的多媒体素材管理系统
spring boot·python·django·flask·node.js·php
a***59263 小时前
SpringBoot实现异步调用的方法
java·spring boot·spring
龙智DevSecOps解决方案3 小时前
Java开发基础:什么是Spring Boot?一文了解其优势、对比以及如何通过Perforce JRebel实现高效开发
java·开发语言·spring boot·jrebel·perforce·java开发