跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像AI 生图工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
Javajava

Spring Boot 消息队列与异步通信

Spring Boot 消息队列与异步通信的核心概念与使用方法。内容涵盖消息队列的定义、特点及常见中间件(ActiveMQ、RabbitMQ、Kafka)的集成步骤与代码示例,包括依赖配置、生产者、消费者及测试类实现。同时讲解了 Spring Boot 异步通信的两种基本方法:@Async 注解和 CompletableFuture,并结合用户注册场景演示了实际应用。旨在帮助开发者掌握在 Spring Boot 环境下利用消息队列实现系统解耦、提升性能的方案。

咸鱼开飞机发布于 2026/3/30更新于 2026/7/939 浏览
Spring Boot 消息队列与异步通信

Spring Boot 消息队列与异步通信

消息队列概述

消息队列的定义

定义:消息队列是一种异步通信机制,用于在应用程序之间传递消息。

作用:

  • 实现应用程序之间的异步通信。
  • 实现应用程序之间的解耦。
  • 提高应用程序的性能。

常见的消息队列:

  • ActiveMQ:Apache ActiveMQ 是一款开源的消息队列。
  • RabbitMQ:RabbitMQ 是一款开源的消息队列。
  • Kafka:Apache Kafka 是一款开源的消息队列。

结论:消息队列是一种异步通信机制,作用是实现应用程序之间的异步通信、解耦、提高应用程序的性能。

消息队列的特点

特点:

  • 异步通信:消息发送者不需要等待消息接收者的响应。
  • 解耦:消息发送者与消息接收者之间不需要直接通信。
  • 可靠性:消息队列提供消息的可靠传输。
  • 可扩展性:消息队列可以扩展到多个应用程序之间的通信。

结论:消息队列的特点包括异步通信、解耦、可靠性、可扩展性。

Spring Boot 与 ActiveMQ 集成

集成步骤

  1. 创建 Spring Boot 项目。
  2. 添加所需的依赖。
  3. 配置 ActiveMQ。
  4. 创建消息生产者。
  5. 创建消息消费者。
  6. 测试应用。
示例代码

pom.xml 文件中的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties 文件中的 ActiveMQ 配置:

# 服务器端口
server.port=8080
# ActiveMQ 配置
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin

消息生产者:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {
    @Autowired
    private JmsTemplate jmsTemplate;

    public void sendMessage(String destination, String message) {
        jmsTemplate.convertAndSend(destination, message);
        System.out.println("发送消息:" + message);
    }
}

消息消费者:

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer {
    @JmsListener(destination = "test-queue")
    public void receiveMessage(String message) {
        System.out.println("接收消息:" + message);
    }
}

控制器类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {
    @Autowired
    private MessageProducer messageProducer;

    @GetMapping("/send")
    public String sendMessage(@RequestParam String message) {
        messageProducer.sendMessage("test-queue", message);
        return "消息发送成功";
    }
}

结论:集成 ActiveMQ 的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置 ActiveMQ、创建消息生产者、创建消息消费者、测试应用。

Spring Boot 与 RabbitMQ 集成

集成步骤

  1. 创建 Spring Boot 项目。
  2. 添加所需的依赖。
  3. 配置 RabbitMQ。
  4. 创建消息生产者。
  5. 创建消息消费者。
  6. 测试应用。
示例代码

pom.xml 文件中的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties 文件中的 RabbitMQ 配置:

# 服务器端口
server.port=8080
# RabbitMQ 配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

消息生产者:

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String exchange, String routingKey, String message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        System.out.println("发送消息:" + message);
    }
}

消息消费者:

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer {
    @RabbitListener(queues = "test-queue")
    public void receiveMessage(String message) {
        System.out.println("接收消息:" + message);
    }
}

RabbitMQ 配置类:

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    @Bean
    public Queue testQueue() {
        return new Queue("test-queue", true);
    }

    @Bean
    public DirectExchange testExchange() {
        return new DirectExchange("test-exchange");
    }

    @Bean
    public Binding testBinding() {
        return BindingBuilder.bind(testQueue()).to(testExchange()).with("test-routing-key");
    }
}

结论:集成 RabbitMQ 的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置 RabbitMQ、创建消息生产者、创建消息消费者、测试应用。

Spring Boot 与 Kafka 集成

集成步骤

  1. 创建 Spring Boot 项目。
  2. 添加所需的依赖。
  3. 配置 Kafka。
  4. 创建消息生产者。
  5. 创建消息消费者。
  6. 测试应用。
示例代码

pom.xml 文件中的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties 文件中的 Kafka 配置:

# 服务器端口
server.port=8080
# Kafka 配置
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=test-group
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

消息生产者:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendMessage(String topic, String message) {
        kafkaTemplate.send(topic, message);
        System.out.println("发送消息:" + message);
    }
}

消息消费者:

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer {
    @KafkaListener(topics = "test-topic", groupId = "test-group")
    public void receiveMessage(String message) {
        System.out.println("接收消息:" + message);
    }
}

结论:集成 Kafka 的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置 Kafka、创建消息生产者、创建消息消费者、测试应用。

Spring Boot 异步通信的基本方法

Spring Boot 异步通信的基本方法包括使用@Async 注解、使用 CompletableFuture、使用消息队列。

使用@Async 注解

作用:

  • 实现异步通信。
  • 提高应用程序的性能。
示例代码

异步配置类:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfig {}

异步服务类:

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    @Async
    public void asyncMethod() {
        System.out.println("异步方法执行:" + Thread.currentThread().getName());
    }
}

控制器类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async")
    public String asyncMethod() {
        System.out.println("主线程执行:" + Thread.currentThread().getName());
        asyncService.asyncMethod();
        return "异步方法调用成功";
    }
}

结论:使用@Async 注解是指使用 Spring Boot 异步通信的基本方法之一,作用是实现异步通信、提高应用程序的性能。

使用 CompletableFuture

作用:

  • 实现异步通信。
  • 提高应用程序的性能。
示例代码

控制器类:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class CompletableFutureController {
    @GetMapping("/completableFuture")
    public String completableFuture() throws ExecutionException, InterruptedException {
        System.out.println("主线程执行:" + Thread.currentThread().getName());
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("异步方法执行:" + Thread.currentThread().getName());
        });
        future.get();
        return "CompletableFuture 调用成功";
    }
}

结论:使用 CompletableFuture 是指使用 Spring Boot 异步通信的基本方法之一,作用是实现异步通信、提高应用程序的性能。

Spring Boot 的实际应用场景

在实际开发中,Spring Boot 消息队列与异步通信的应用场景非常广泛,如:

  • 实现用户注册的异步处理。
  • 实现订单的异步处理。
  • 实现邮件发送的异步处理。
  • 实现日志的异步处理。
示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableAsync
public class UserRegistrationApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserRegistrationApplication.class, args);
    }
}

@Service
class UserRegistrationService {
    @Async
    public void sendWelcomeEmail(String email) {
        System.out.println("发送欢迎邮件:" + email);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("邮件发送成功:" + email);
    }
}

@RestController
class UserRegistrationController {
    @Autowired
    private UserRegistrationService userRegistrationService;

    @GetMapping("/register")
    public String registerUser(String email) {
        System.out.println("用户注册:" + email);
        userRegistrationService.sendWelcomeEmail(email);
        return "用户注册成功";
    }
}

控制台输出:

用户注册:test@example.com
发送欢迎邮件:test@example.com
邮件发送成功:test@example.com

结论:在实际开发中,Spring Boot 消息队列与异步通信的应用场景非常广泛,需要根据实际问题选择合适的异步通信方法。

总结

本章我们学习了 Spring Boot 消息队列与异步通信,包括消息队列的定义与特点、Spring Boot 与 ActiveMQ 的集成、Spring Boot 与 RabbitMQ 的集成、Spring Boot 与 Kafka 的集成、Spring Boot 异步通信的基本方法、Spring Boot 的实际应用场景,学会了在实际开发中处理消息队列与异步通信问题。其中,消息队列的定义与特点、Spring Boot 与 ActiveMQ 的集成、Spring Boot 与 RabbitMQ 的集成、Spring Boot 与 Kafka 的集成、Spring Boot 异步通信的基本方法、Spring Boot 的实际应用场景是本章的重点内容。从下一章开始,我们将学习 Spring Boot 的其他组件、微服务等内容。

目录

  1. Spring Boot 消息队列与异步通信
  2. 消息队列概述
  3. 消息队列的定义
  4. 消息队列的特点
  5. Spring Boot 与 ActiveMQ 集成
  6. 集成步骤
  7. 示例代码
  8. 服务器端口
  9. ActiveMQ 配置
  10. Spring Boot 与 RabbitMQ 集成
  11. 集成步骤
  12. 示例代码
  13. 服务器端口
  14. RabbitMQ 配置
  15. Spring Boot 与 Kafka 集成
  16. 集成步骤
  17. 示例代码
  18. 服务器端口
  19. Kafka 配置
  20. Spring Boot 异步通信的基本方法
  21. 使用@Async 注解
  22. 示例代码
  23. 使用 CompletableFuture
  24. 示例代码
  25. Spring Boot 的实际应用场景
  26. 示例代码
  27. 总结
  • 免费图片AI生成工具免费生成了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 免费图片视频在线生成30秒,将你的创意变成现实开始设计
  • X/Twitter免费视频下载器免登陆无限额度免费视频解析下载了解详情
  • 100+免费在线小游戏爽一把
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • 基于 DeepSeek 和 Cursor 构建智能代码审查工具实战
  • SDXL Prompt Styler 提示词增强工具使用指南
  • Java 使用 Spire.PDF 解析 PDF 文本、表格、图像及元数据
  • Spring Boot Web 三大核心交互实战:表单、AJAX 与 JSON
  • Python 开源 AI 模型引入与测试实战
  • Python HTTP 请求库对比:requests、aiohttp 与 httpx
  • 大厂 Android 开发核心面试题汇总
  • LLaMA 大模型 LoRA 微调实践与心得
  • 数据结构:树、森林与二叉树的转换详解
  • OpenSpec 实战:用规范驱动开发破解 AI 编程协作难题
  • 前端拖拽交互实现:从原生 API 到专业库
  • DeepSeek-R1-Distill-Llama-8B 模型安全与对抗攻击防护
  • Flutter Genkit 在鸿蒙端的适配:模型幻觉审计与端云协同 AI 方案
  • 可解释人工智能:从经典模型到大规模语言模型全解析
  • 队列详解:从概念到 C 语言实战
  • Linux 进程管理进阶:会话、进程组与守护进程的底层逻辑与实践
  • 大模型训练存储优化:Unified Checkpoint 技术详解
  • GLM 语言模型原理与代码实例
  • Git 核心原理与基础操作详解 (上)
  • Java 基于 YOLO 框架的视频 AI 识别算法平台,适配无人机巡检与安防场景

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online