RabbitMq 集成 spring boot 消息队列 入门Demo

简介:

spring boot 集成 RabbitMq还是很方便的。现在来一个简单的例子来集成rabbitmq。入门demo。

主要概念:

其中比较重要的概念有 4 个,分别为:虚拟主机,交换机,队列,和绑定。


虚拟主机:一个虚拟主机持有一组交换机、队列和绑定。为什么需要多个虚拟主机呢?很简单,RabbitMQ当中,用户只能在虚拟主机的粒度进行权限控制。 因此,如果需要禁止A组访问B组的交换机/队列/绑定,必须为A和B分别创建一个虚拟主机。每一个RabbitMQ服务器都有一个默认的虚拟主机“/”。

交换机:Exchange 用于转发消息,但是它不会做存储 ,如果没有 Queue bind 到 Exchange 的话,它会直接丢弃掉 Producer 发送过来的消息。 这里有一个比较重要的概念:路由键 。消息到交换机的时候,交互机会转发到对应的队列中,那么究竟转发到哪个队列,就要根据该路由键。

绑定:也就是交换机需要和队列相绑定,这其中如上图所示,是多对多的关系。


首先是配制文件。

1
2
3
4
5
#spring.application.name=spring-boot-rabbitmq
spring.rabbitmq.host= 127.0 . 0.1
spring.rabbitmq.port= 5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest


发送者:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package  com.basic.rabbitmq.send;
 
import  com.basic.rabbitmq.configuration.RabbitMqConfig2;
import  org.springframework.amqp.core.AmqpTemplate;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.stereotype.Component;
import  org.springframework.stereotype.Service;
 
import  java.util.Date;
 
/**
  * Created by sdc on 2017/6/17.
  */
@Service ( "helloSender" )
public  class  HelloSender {
 
     @Autowired
     private  AmqpTemplate amqpTemplate;
 
//    private Rabbitt
 
     public  void  send() {
         String contenxt =  "order_queue_message" ;
         this .amqpTemplate.convertAndSend(RabbitMqConfig2.QUEUE_EXCHANGE_NAME, "order_queue_routing" ,contenxt);
//        this.amqpTemplate.conver
     }
 
}


配制信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package  com.basic.rabbitmq.configuration;
 
import  com.basic.rabbitmq.receiver.Receiver;
import  com.rabbitmq.client.Channel;
import  com.rabbitmq.client.ConfirmListener;
import  org.springframework.amqp.core.*;
import  org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import  org.springframework.amqp.rabbit.connection.ConnectionFactory;
import  org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import  org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import  org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import  org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import  org.springframework.context.annotation.Bean;
import  org.springframework.context.annotation.Configuration;
 
import  java.io.IOException;
 
/**
  * Created by sdc on 2017/6/17.
  */
@Configuration
public  class  RabbitMqConfig2 {
 
     public  static  final  String QUEUE_NAME =  "order_queue" ;
 
     public  static  final  String QUEUE_EXCHANGE_NAME =  "topic_exchange_new" ;
 
     public  static  final   String routing_key =  "order_queue_routing" ;
 
     @Bean
     public  Queue queue() {
         //是否持久化
         boolean  durable =  false ;
         //仅创建者可以使用该队列,断开后自动删除
         boolean  exclusive =  false ;
         //当所有消费者都断开连接后,是否删除队列
         boolean  autoDelete =  false ;
         return  new  Queue(QUEUE_NAME, durable, exclusive, autoDelete);
     }
 
     @Bean
     public  TopicExchange exchange() {
         //是否持久化
         boolean  durable =  false ;
         //当所有消费者都断开连接后,是否删除队列
         boolean  autoDelete =  false ;
         return   new  TopicExchange(QUEUE_EXCHANGE_NAME, durable, autoDelete);
     }
 
     @Bean
     public  Binding binding() {
         return  BindingBuilder.bind(queue()).to(exchange()).with(routing_key);
     }
 
     @Bean
     public  ConnectionFactory connectionFactory() {
         CachingConnectionFactory connectionFactory =  new  CachingConnectionFactory( "127.0.0.1" , 5672 );
 
         connectionFactory.setUsername( "admin" );
         connectionFactory.setPassword( "admin" );
         connectionFactory.setVirtualHost( "/" );
         /** 如果要进行消息回调,则这里必须要设置为true */
         connectionFactory.setPublisherConfirms( true );  // 必须要设置
//        connectionFactory.setPublisherReturns();
         return  connectionFactory;
     }
 
     @Bean
     SimpleMessageListenerContainer container() {
 
         SimpleMessageListenerContainer container =  new  SimpleMessageListenerContainer();
         container.setConnectionFactory(connectionFactory());
//        container.setQueueNames(QUEUE_NAME);
         container.setQueues(queue());
         container.setAcknowledgeMode(AcknowledgeMode.MANUAL);  //设置确认模式手工确认
         container.setMessageListener( new  ChannelAwareMessageListener() {
             @Override
             public  void  onMessage(Message message, Channel channel)  throws  Exception {
                 byte [] body = message.getBody();
                 System.out.println( "收到消息 : "  new  String(body));
                 channel.queueDeclare(QUEUE_NAME,  true false false null );
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
//                channel.basicAck(); //应答
//                channel.basicReject();//拒绝
//                channel.basicRecover(); //恢复
//                channel.basicQos();
//                channel.addConfirmListener(new ConfirmListener() {
//                    @Override
//                    public void handleAck(long deliveryTag, boolean multiple) throws IOException {
//                        //失败重发
//                    }
//
//                    @Override
//                    public void handleNack(long deliveryTag, boolean multiple) throws IOException {
//                        //确认ok
//                    }
//                });
             }
         });
         return   container;
     }
 
//    @Bean
//    MessageListenerAdapter listenerAdapter(Receiver receiver) {
//        return new MessageListenerAdapter(receiver, "receiveMessage");
//    }
 
}


测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package  com.rabbit.test;
 
import  com.basic.rabbitmq.send.HelloSender;
import  com.basic.system.Application;
import  org.junit.Test;
import  org.junit.runner.RunWith;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.boot.test.context.SpringBootTest;
import  org.springframework.test.context.junit4.SpringRunner;
 
import  javax.annotation.Resource;
 
/**
  * Created by sdc on 2017/6/17.
  */
@RunWith(SpringRunner. class )
@SpringBootTest(classes = Application. class )
public  class  RabbitMqTest {
 
     @Autowired
     public  HelloSender helloSender;
 
     @Test
     public  void helloword() throws  Exception {
         helloSender.send();
     }
 
 
}


这只是一个demo,学习的时候会测试各种的事情,在这基础上更改就可以了,心中的疑虑测试没了就可以写一些项目了。


本文转自 豆芽菜橙 51CTO博客,原文链接:http://blog.51cto.com/shangdc/1944218


相关实践学习
快速体验阿里云云消息队列RocketMQ版
本实验将带您快速体验使用云消息队列RocketMQ版Serverless系列实例进行获取接入点、创建Topic、创建订阅组、收发消息、查看消息轨迹和仪表盘。
消息队列 MNS 入门课程
1、消息队列MNS简介 本节课介绍消息队列的MNS的基础概念 2、消息队列MNS特性 本节课介绍消息队列的MNS的主要特性 3、MNS的最佳实践及场景应用 本节课介绍消息队列的MNS的最佳实践及场景应用案例 4、手把手系列:消息队列MNS实操讲 本节课介绍消息队列的MNS的实际操作演示 5、动手实验:基于MNS,0基础轻松构建 Web Client 本节课带您一起基于MNS,0基础轻松构建 Web Client
相关文章
|
11月前
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
3099 1
|
11月前
|
消息中间件 Java Kafka
消息队列比较:Spring 微服务中的 Kafka 与 RabbitMQ
本文深入解析了 Kafka 和 RabbitMQ 两大主流消息队列在 Spring 微服务中的应用与对比。内容涵盖消息队列的基本原理、Kafka 与 RabbitMQ 的核心概念、各自优势及典型用例,并结合 Spring 生态的集成方式,帮助开发者根据实际需求选择合适的消息中间件,提升系统解耦、可扩展性与可靠性。
706 1
消息队列比较:Spring 微服务中的 Kafka 与 RabbitMQ
|
消息中间件 安全 Java
云消息队列RabbitMQ实践解决方案评测
一文带你详细了解云消息队列RabbitMQ实践的解决方案优与劣
621 111
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
2751 0
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
460 6
|
消息中间件 存储 弹性计算
云消息队列RabbitMQ实践
云消息队列RabbitMQ实践
|
消息中间件
解决方案 | 云消息队列RabbitMQ实践获奖名单公布!
云消息队列RabbitMQ实践获奖名单公布!
331 1
|
消息中间件 存储 监控
解决方案 | 云消息队列RabbitMQ实践
在实际业务中,网站因消息堆积和高流量脉冲导致系统故障。为解决这些问题,云消息队列 RabbitMQ 版提供高性能的消息处理和海量消息堆积能力,确保系统在流量高峰时仍能稳定运行。迁移前需进行技术能力和成本效益评估,包括功能、性能、限制值及费用等方面。迁移步骤包括元数据迁移、创建用户、网络打通和数据迁移。
519 4

相关产品

  • 云消息队列 MQ