SpringBoot如何使用Kafka来优化接口请求的并发

在Spring Boot中使用 Kafka 来优化接口请求的并发,主要是通过将耗时的任务异步化到Kafka消息队列中来实现。这样,接口可以立即响应客户端,而不需要等待耗时任务完成。

在Spring Boot应用程序中调用Kafka通常涉及使用Spring Kafka库,它提供了与Apache Kafka的高级集成,使得从Spring Boot应用程序中发送和接收消息变得更加简单和直观。

安装Apache Kafka

编写docker-compose.yml

bash 复制代码
version: '3'
services:
  zookeeper:
    image: wurstmeister/zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka
    container_name: kafka
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_HOST_NAME: localhost
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

使用docker compose启动容器

bash 复制代码
docker-compose up -d

添加依赖

首先,需要在pom.xml中添加Spring Kafka的依赖。

XML 复制代码
<!-- Spring Kafka -->
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
</dependency>

配置Kafka

在application.properties文件中配置Kafka的属性。

bash 复制代码
# application.properties  
spring.kafka.bootstrap-servers=localhost:9092  
spring.kafka.consumer.group-id=myGroup  
spring.kafka.consumer.auto-offset-reset=earliest  
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer  
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer  
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer  
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer

Kafka生产者服务

创建一个服务类来发送消息到Kafka。

java 复制代码
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;

    public void sendMessage(String topic, String key, String value) {
        // 异步发送消息
        kafkaTemplate.send(topic, key, value).addCallback(success -> {
            System.out.println("Message sent successfully: " + value);
        }, failure -> {
            System.err.println("Failed to send message: " + value);
        });
    }
}

Kafka消费者服务

创建一个监听器来接收Kafka中的消息。

java 复制代码
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class KafkaConsumerService {

    @KafkaListener(topics = "your-topic-name", groupId = "myGroup")
    public void listen(String message) {
        // 处理消息(可能是耗时的操作)
        System.out.println("Received message in group 'myGroup': " + message);
        // 处理耗时操作
        ...
    }
}

控制器

在控制器中调用Kafka生产者服务来发送消息,并立即响应客户端。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
  
@RestController
public class MyController {

    @Autowired  
    private KafkaProducerService kafkaProducerService;

    @PostMapping("/send")
    public String sendMessage(@RequestParam String message) {
        // 发送消息到Kafka,并立即返回响应
        kafkaProducerService.sendMessage("your-topic-name", "key1", message);
        return "Message sent to Kafka";
    }
}
相关推荐
白萤8 小时前
SpringBoot用户登录注册系统设计与实现
java·spring boot·后端
摇滚侠11 小时前
Spring Boot 3零基础教程,创建第一个 Spring Boot 3 应用,Spring Boot 3 外部配置,笔记03
java·spring boot·笔记
笨手笨脚の20 小时前
Kafka-1 初识消息引擎系统
分布式·kafka·消息队列·消息引擎系统
深色風信子21 小时前
SpringBoot 集成 LangChain4j RAG Redis 搜索
spring boot·langchain4j rag·rag redis 搜索·rag redis·springboot rag·rag 搜索
Savvy..21 小时前
消息队列MQ
kafka·消息队列·rabbitmq·rocketmq·mq
小蒜学长21 小时前
springboot餐厅信息管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端
Jabes.yang1 天前
Java大厂面试实录:从Spring Boot到微服务的技术探讨
java·spring boot·spring cloud·微服务·技术面试
235161 天前
【MQ】RabbitMQ:架构、工作模式、高可用与流程解析
java·分布式·架构·kafka·rabbitmq·rocketmq·java-rabbitmq
咖啡Beans1 天前
SpringBoot集成MongoDB使用
spring boot·mongodb