springboot 整合kafka,实现发送提醒消息

简介: springboot 整合kafka,实现发送提醒消息

Spring Boot 整合 Kafka 发送提醒消息

整合 Spring Boot 和 Kafka 实现发送提醒消息,可以帮助你在分布式系统中实现高效的消息传递和处理。以下是完整的整合过程,包括依赖配置、Kafka 生产者和消费者的实现,以及测试代码。

1. 添加依赖

首先,在 pom.xml 中添加 Kafka 和 Spring for Apache Kafka 的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
</dependencies>
2. 配置 Kafka

application.yml 中配置 Kafka 相关属性:

spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      group-id: group_id
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
3. 创建 Kafka 生产者配置类

创建一个 KafkaProducerConfig 类,用于配置 Kafka 生产者:

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
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 org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;
 
@Configuration
public class KafkaProducerConfig {
 
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }
 
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}
4. 创建 Kafka 消费者配置类

创建一个 KafkaConsumerConfig 类,用于配置 Kafka 消费者:

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import java.util.HashMap;
import java.util.Map;
 
@EnableKafka
@Configuration
public class KafkaConsumerConfig {
 
    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configProps.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id");
        configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return new DefaultKafkaConsumerFactory<>(configProps);
    }
 
    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }
}
5. 创建 Kafka 生产者服务

创建一个 KafkaProducerService 类,用于发送消息:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
 
@Service
public class KafkaProducerService {
 
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
 
    private static final String TOPIC = "reminder_topic";
 
    public void sendMessage(String message) {
        kafkaTemplate.send(TOPIC, message);
    }
}
6. 创建 Kafka 消费者监听器

创建一个 KafkaConsumerListener 类,用于接收消息:

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
 
@Service
public class KafkaConsumerListener {
 
    @KafkaListener(topics = "reminder_topic", groupId = "group_id")
    public void listen(String message) {
        System.out.println("Received Message: " + message);
        // 在这里处理消息,例如发送提醒
    }
}
7. 创建控制器发送消息

创建一个 ReminderController 类,通过 REST API 接收请求并发送 Kafka 消息:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/api/reminder")
public class ReminderController {
 
    @Autowired
    private KafkaProducerService producerService;
 
    @PostMapping("/send")
    public String sendReminder(@RequestBody String message) {
        producerService.sendMessage(message);
        return "Message sent to Kafka Topic";
    }
}
8. 测试代码

创建一个简单的测试类 ReminderControllerTest,测试发送提醒消息:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
 
@SpringBootTest
@AutoConfigureMockMvc
public class ReminderControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void testSendReminder() throws Exception {
        String message = "This is a test reminder";
 
        mockMvc.perform(post("/api/reminder/send")
                .content(message)
                .contentType("text/plain"))
                .andExpect(status().isOk());
    }
}

总结

以上是整合 Spring Boot 和 Kafka 发送提醒消息的完整过程。通过上述步骤,你可以实现一个简单的分布式消息系统,发送和接收提醒消息。可以根据需要扩展和优化该系统,例如添加更多的消费者处理逻辑,增加消息处理的可靠性等。

参考资料

通过上述示例代码,你应该能够快速上手并实现 Spring Boot 与 Kafka 的整合。如果有进一步的问题或需要更详细的解释,请随时询问。


目录
打赏
0
1
1
0
36
分享
相关文章
【Azure Kafka】使用Spring Cloud Stream Binder Kafka 发送并接收 Event Hub 消息及解决并发报错
reactor.core.publisher.Sinks$EmissionException: Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially.
【实操】SpringBoot监听Iphone15邮件提醒,Selenium+Python自动化抢购脚本
本文介绍了一个结合SpringBoot和Python的实用功能,旨在监控iPhone 15的库存状态并通过邮件提醒用户。系统采用SpringBoot监听苹果官网API,解析JSON数据判断是否有货,并展示最近的库存记录。此外,还能自动触发Selenium+Python脚本实现自动化购买。文中详细介绍了技术栈、接口分析、邮件配置及自动化脚本的设置方法。该项目不仅适用于熟悉后端开发的人员,也适合回顾Layui和Jquery等前端技术。
87 0
【实操】SpringBoot监听Iphone15邮件提醒,Selenium+Python自动化抢购脚本
什么是Apache Kafka?如何将其与Spring Boot集成?
什么是Apache Kafka?如何将其与Spring Boot集成?
141 5
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
102 1
大数据-56 Kafka SpringBoot与Kafka 基础简单配置和使用 Java代码 POM文件
大数据-56 Kafka SpringBoot与Kafka 基础简单配置和使用 Java代码 POM文件
116 2
掌握这一招,Spring Boot与Kafka完美融合,顺序消费不再是难题,让你轻松应对业务挑战!
【8月更文挑战第29天】Spring Boot与Kafka集成广泛用于处理分布式消息队列。本文探讨了在Spring Boot中实现Kafka顺序消费的方法,包括使用单个Partition或消息Key确保消息路由到同一Partition,并设置Consumer并发数为1以保证顺序消费。通过示例代码展示了如何配置Kafka Producer和Consumer,并自定义Partitioner。为确保数据正确性,还建议在业务逻辑中增加顺序校验机制。
318 3
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等