简介
说明
本文用示例介绍SpringBoot如何整合RabbitMQ。(队列、交换器等信息自动注册)。
官网
Spring AMQP 2.1.2.RELEASE 中文文档 – 1. Preface | Docs4dev
为什么要自动注册?
Java中高级应该做的事是:自动化、高级化、智能化、低bug。
如果不用自动注册,会遇到如下问题:
- 需要手动去MQ控制台添加队列等,很麻烦,且容易出问题
- 一般有多个环境:测试、预发布、生产,每一个都要去手动加,太麻烦了!
- 如果队列被人误删或者丢失了,很难发现,一发现就是大问题。
而用自动注册,则会完全解决上边的问题:项目启动后自动去MQ服务端注册(如果MQ服务器上没有就去注册,如果已经有了就不处理)。代码只要合到相应分支即可。
效果展示
运行服务
运行sender服务(生产者)
server: port: 9100 # port: 9101 spring: application: name: demo-rabbitmq-sender # name: demo-rabbitmq-receiver rabbitmq: host: localhost port: 5672 username: admin password: 123456 # virtualHost: /
运行receiver服务(消费者)
server: # port: 9100 port: 9101 spring: application: # name: demo-rabbitmq-sender name: demo-rabbitmq-receiver rabbitmq: host: localhost port: 5672 username: admin password: 123456 # virtualHost: /
MQ页面
测试1:基础功能
测试内容
测试只获得数据(payload)。
postman访问:http://localhost:9100/hi
receiver打印结果
Receiver(hi) : hi message:2020-10-21T18:52:24.766
postman访问:http://localhost:9100/hello1
receiver打印结果:无打印
即:若队列已经与交换器绑定,则必须指定交换器和路由键。
postman访问:Node Exporter
receiver打印结果
Receiver(hello) : hello2 message:2020-10-21T18:52:41.434
测试2:测试详细数据
测试内容
测试获得payload/message/channel。
使用receiver的第二种代码。
postman访问:http://localhost:9100/hi
receiver打印结果
Receiver(hi): payload:hi1 message:2020-10-22T15:41:11.796 message:(Body:'hi1 message:2020-10-22T15:41:11.796' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=Queue@hi, deliveryTag=1, consumerTag=amq.ctag-K0Yka5vHxrq6JzNXlg3ncQ, consumerQueue=Queue@hi]) channel:Cached Rabbit Channel: AMQChannel(amqp://admin@127.0.0.1:5672/,1), conn: Proxy@4f4c88f9 Shared Rabbit Connection: SimpleConnection@7c52fc81 [delegate=amqp://admin@127.0.0.1:5672/, localPort= 62067]
postman访问:http://localhost:9100/hello1
receiver打印结果:无打印
即:若队列已经与交换器绑定,则必须指定交换器和路由键。
postman访问:http://localhost:9100/hello2
receiver打印结果
Receiver(hello): payload:hello2 message:2020-10-22T15:42:13.126 message:(Body:'hello2 message:2020-10-22T15:42:13.126' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=Exchange@topic.welcome, receivedRoutingKey=hello.b, deliveryTag=1, consumerTag=amq.ctag-yZryIR801zNV5f0f9mJd9g, consumerQueue=Queue@hello]) channel:Cached Rabbit Channel: AMQChannel(amqp://admin@127.0.0.1:5672/,2), conn: Proxy@4f4c88f9 Shared Rabbit Connection: SimpleConnection@7c52fc81 [delegate=amqp://admin@127.0.0.1:5672/, localPort= 62067]
1.安装RabbitMQ
方法1:Windows直接安装
方法2:用docker安装
见:Docker Compose-安装RabbitMQ-方法/示例 – 自学精灵
2.代码
此内容仅限VIP查看,请先登录
请先
!