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;
    }
}
相关推荐
码界奇点18 小时前
基于Spring Boot和微信小程序的小程序商城系统设计与实现
spring boot·微信小程序·小程序·毕业设计·源代码管理
+VX:Fegn089519 小时前
计算机毕业设计|基于springboot + vue英语学习系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
伯明翰java19 小时前
【无标题】springboot项目yml中使用中文注释报错的解决方法
java·spring boot·后端
码界奇点19 小时前
基于Spring Boot和Vue.js的视频点播管理系统设计与实现
java·vue.js·spring boot·后端·spring·毕业设计·源代码管理
廋到被风吹走19 小时前
【Spring】Spring Boot详细介绍
java·spring boot·spring
czlczl2002092519 小时前
基于 Spring Boot 权限管理 RBAC 模型
前端·javascript·spring boot
计算机毕设指导619 小时前
基于微信小程序的智慧社区娱乐服务管理系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·娱乐
Wang's Blog20 小时前
Kafka: 高吞吐量原理、应用场景
分布式·kafka
东东的脑洞20 小时前
【面试突击】Kafka 核心面试知识点
面试·职场和发展·kafka
赵得C20 小时前
Spring Boot+MyBatis:用 PageHelper 实现 Oracle 12c 的 OFFSET 分页
spring boot·oracle·mybatis