博客
关于我
SpringBoot之RabbitMQ的简单使用的Demo
阅读量:335 次
发布时间:2019-03-04

本文共 2314 字,大约阅读时间需要 7 分钟。

Spring Boot 与 RabbitMQ 快速入门指南

1. 基本声明

本文旨在提供使用 RabbitMQ 的基本操作指导,基于 Spring Boot 框架进行配置和使用。本文将从环境搭建、依赖管理、配置文件设置、消息发送与接收等方面进行详细说明。

2. RabbitMQ 账户配置

在使用 RabbitMQ 之前,需要先创建一个测试账户。注意:在创建账户时,虚拟主机host 必须设置为 /,否则可能会导致连接失败。这里以 root 作为测试账户。

3. 项目依赖管理

在项目的 pom.xml 文件中添加必要的依赖项:

org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
/
com.example
SpringBoot-RabbitMQ
0.0.1-SNAPSHOT
jar
http://maven.apache.org
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-amqp
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-maven-plugin

4. 应用配置

在项目根目录下创建 application.properties 文件,并添加以下内容:

spring.application.name=rabbitmq-helloserver.port=8080spring.rabbitmq.host=localhostspring.rabbitmq.port=5672spring.rabbitmq.username=rootspring.rabbitmq.password=root

5. 主程序实现

创建 RabbitMQApplication.java 文件:

@RestController@SpringBootApplicationpublic class RabbitMQApplication {    @Autowired    private AmqpTemplate amqpTemplate;    @RequestMapping("/send")    public String send(String msg) {        amqpTemplate.convertAndSend("test", msg);        return "发送消息成功:" + msg;    }    public static void main(String[] args) {        SpringApplication.run(RabbitMQApplication.class, args);    }    @Bean    public Queue queue() {        return new Queue("test");    }    @Component    @RabbitListener(queues = "test")    public class MsgCustomer {        @RabbitHandler        public void handlerMsg(String msg) {            System.out.println("消息消费者消费:" + msg);        }    }}

6. 测试与验证

发送消息:

  • 访问 http://localhost:8080/send,输入消息内容,点击发送。
  • 打开 RabbitMQ 管理界面,查看消息队列,确认消息已成功发送至 test 队列。

消息消费:

  • 在 RabbitMQ 的管理界面中,确认 test 队列有无消费者接收消息。
  • 消息会自动由 MsgCustomer 类的 handlerMsg 方法处理,输出在控制台。

7. 总结与建议

本文详细介绍了如何在 Spring Boot 项目中集成 RabbitMQ,实现了消息的发布与订阅功能。通过本文,您可以快速上手 RabbitMQ 的使用,进行消息队列开发。对于更复杂的场景,可以参考 RabbitMQ 的官方文档或相关技术博客,进一步优化消息系统的性能和可靠性。

转载地址:http://rwrh.baihongyu.com/

你可能感兴趣的文章
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>