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;
    }
}
相关推荐
mygljx3 小时前
SpringBoot+Mybatis-plus实现分页查询(一看就会)
spring boot·mybatis·状态模式
彭于晏Yan11 小时前
Redisson分布式锁
spring boot·redis·分布式
ywf121513 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
独断万古他化15 小时前
【Java 实战项目】多用户网页版聊天室:消息传输模块 —— 基于 WebSocket 实现实时通信
java·spring boot·后端·websocket·ajax·mybatis
Sweet锦15 小时前
SpringBoot 3.5 集成 InfluxDB 1.8
spring boot·时序数据库
Java水解16 小时前
Spring Boot 消息队列与异步处理
spring boot·后端
深蓝轨迹19 小时前
黑马点评--达人探店模块
java·spring boot·redis
菜鸟程序员专写BUG19 小时前
SpringBoot 接口返回异常全集|JSON解析失败/响应乱码/状态码错误完美解决
spring boot·后端·json
希望永不加班20 小时前
SpringBoot 编写第一个 REST 接口(Get/Post/Put/Delete)
java·spring boot·后端·spring
vx-程序开发20 小时前
springboot智慧农业信息服务平台-计算机毕业设计源码65287
spring boot·后端·课程设计