spring整合RabbitMQ
今天就来康康spring怎么整合RabbitMQ
注意一点,在发送消息的时候对template进行配置mandatory=true保证监听有效
生产端还可以配置其他属性,比如发送重试,超时时间、次数、间隔等
消费端核心配置
- 首先配置手工确认模式,用于ACK的手工处理,这样我们可以保证消息的可靠性送达,或者在消费端消费失败的时候可以做到重回队列、根据业务记录日志等处理
- 可以设置消费端的监听个数和最大个数,用于控制消费端的并发情况
@RabbitListener注解的使用
消费端监听@RabbitListener注解,这个对于在实际工作中非常的好用
@RabbitListener是一个组合注解,里面可以注
解配置(@QueueBinding、@Queue、@Exchange)直接通过这个组合注解一次性搞定消费端交换机、队列、绑定、路由、并且配置监听功能等
注:由于类配置写在代码里非常不友好,所以强烈建议大家使用配置文件配置
创建一个
rabbitmq-common通用模板项目
放公用实体类
package com.javaxh.rabbitmqcommon.entity;
import java.io.Serializable;
public class Order implements Serializable { private String id;
private String name; public Order() {
}
public Order(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建
rabbitmq-springcloud-consumer子项目
pom文件中添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>com.javaxh</groupId>
<artifactId>rabbitmq-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
application.properties配置
spring.rabbitmq.addresses=192.168.239.131:
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout= server.port=
server.servlet.context-path=/ spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.concurrency=
spring.rabbitmq.listener.simple.max-concurrency= spring.rabbitmq.listener.order.queue.name=queue-
spring.rabbitmq.listener.order.queue.durable=true
spring.rabbitmq.listener.order.exchange.name=exchange-
spring.rabbitmq.listener.order.exchange.durable=true
spring.rabbitmq.listener.order.exchange.type=topic
spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
spring.rabbitmq.listener.order.key=springboot.*
RabbitReceiver
package com.javaxh.rabbitmqspringcloudconsumer.conusmer;
import com.javaxh.rabbitmqcommon.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component; import java.util.Map;
@Component
public class RabbitReceiver {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue-1",
durable="true"),
exchange = @Exchange(value = "exchange-1",
durable="true",
type= "topic",
ignoreDeclarationExceptions = "true"),
key = "springboot.*"
)
)
@RabbitHandler
public void onMessage(Message message, Channel channel) throws Exception {
System.err.println("--------------------------------------");
System.err.println("消费端Payload: " + message.getPayload());
Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
//手工ACK
channel.basicAck(deliveryTag, false);
} /**
*
* spring.rabbitmq.listener.order.queue.name=queue-2
spring.rabbitmq.listener.order.queue.durable=true
spring.rabbitmq.listener.order.exchange.name=exchange-1
spring.rabbitmq.listener.order.exchange.durable=true
spring.rabbitmq.listener.order.exchange.type=topic
spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
spring.rabbitmq.listener.order.key=springboot.*
* @param order
* @param channel
* @param headers
* @throws Exception
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}",
durable="${spring.rabbitmq.listener.order.queue.durable}"),
exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}",
durable="${spring.rabbitmq.listener.order.exchange.durable}",
type= "${spring.rabbitmq.listener.order.exchange.type}",
ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
key = "${spring.rabbitmq.listener.order.key}"
)
)
@RabbitHandler
public void onOrderMessage(@Payload Order order,
Channel channel,
@Headers Map<String, Object> headers) throws Exception {
System.err.println("--------------------------------------");
System.err.println("消费端order: " + order.getId());
Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
//手工ACK
channel.basicAck(deliveryTag, false);
} }
MainConfig
package com.javaxh.rabbitmqspringcloudconsumer; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan({"com.javaxh.rabbitmqspringcloudconsumer.*"})
public class MainConfig { }
创建
rabbitmq-springcloud-producer子项目
在pom中添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>com.javaxh</groupId>
<artifactId>rabbitmq-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
application.properties配置
spring.rabbitmq.addresses=192.168.239.131:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000 spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.template.mandatory=true
RabbitSender
package com.javaxh.rabbitmqspringcloudproducer.producer; import com.javaxh.rabbitmqcommon.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component; import java.util.Map; @Component
public class RabbitSender { //自动注入RabbitTemplate模板类
@Autowired
private RabbitTemplate rabbitTemplate; //回调函数: confirm确认
final ConfirmCallback confirmCallback = new ConfirmCallback() {
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.err.println("correlationData: " + correlationData);
System.err.println("ack: " + ack);
if(!ack){
System.err.println("异常处理....");
}
}
}; //回调函数: return返回
final ReturnCallback returnCallback = new ReturnCallback() {
@Override
public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
String exchange, String routingKey) {
System.err.println("return exchange: " + exchange + ", routingKey: "
+ routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
}
}; //发送消息方法调用: 构建Message消息
public void send(Object message, Map<String, Object> properties) throws Exception {
MessageHeaders mhs = new MessageHeaders(properties);
Message msg = MessageBuilder.createMessage(message, mhs);
rabbitTemplate.setConfirmCallback(confirmCallback);
rabbitTemplate.setReturnCallback(returnCallback);
//id + 时间戳 全局唯一
CorrelationData correlationData = new CorrelationData("1234567890");
rabbitTemplate.convertAndSend("exchange-1", "springboot.abc", msg, correlationData);
} //发送消息方法调用: 构建自定义对象消息
public void sendOrder(Order order) throws Exception {
rabbitTemplate.setConfirmCallback(confirmCallback);
rabbitTemplate.setReturnCallback(returnCallback);
//id + 时间戳 全局唯一
CorrelationData correlationData = new CorrelationData("0987654321");
rabbitTemplate.convertAndSend("exchange-2", "springboot.def", order, correlationData);
} }
MainConfig
package com.javaxh.rabbitmqspringcloudproducer; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan({"com.javaxh.rabbitmqspringcloudproducer.*"})
public class MainConfig { }
测试代码:
RabbitmqSpringcloudProducerApplicationTests
package com.javaxh.rabbitmqspringcloudproducer;
import com.javaxh.rabbitmqcommon.entity.Order;
import com.javaxh.rabbitmqspringcloudproducer.producer.RabbitSender;
import org.junit.jupiter.api.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 java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; @RunWith(SpringRunner.class)
@SpringBootTest
class RabbitmqSpringcloudProducerApplicationTests { @Autowired
private RabbitSender rabbitSender; private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); @Test
public void testSender1() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("number", "12345");
properties.put("send_time", simpleDateFormat.format(new Date()));
rabbitSender.send("Hello RabbitMQ For Spring Boot!", properties);
} @Test
public void testSender2() throws Exception {
Order order = new Order("001", "第一个订单");
rabbitSender.sendOrder(order);
} }
运行效果:
启动consumer项目,然后在运行测试类中的方法
运行公用模板类传送一个实体类给方法:
谢谢观看!!!
spring整合RabbitMQ的更多相关文章
- RabbitMQ入门到进阶(Spring整合RabbitMQ&SpringBoot整合RabbitMQ)
1.MQ简介 MQ 全称为 Message Queue,是在消息的传输过程中保存消息的容器.多用于分布式系统 之间进行通信. 2.为什么要用 MQ 1.流量消峰 没使用MQ 使用了MQ 2.应用解耦 ...
- RabbitMQ学习总结(7)——Spring整合RabbitMQ实例
1.RabbitMQ简介 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现. 官网:http://www.rabbitmq. ...
- rabbitMQ教程(三) spring整合rabbitMQ代码实例
一.开启rabbitMQ服务,导入MQ jar包和gson jar包(MQ默认的是jackson,但是效率不如Gson,所以我们用gson) 二.发送端配置,在spring配置文件中配置 <?x ...
- rabbitMQ教程(四) spring整合rabbitMQ代码实例
一.开启rabbitMQ服务,导入MQ jar包和gson jar包(MQ默认的是jackson,但是效率不如Gson,所以我们用gson) 二.发送端配置,在spring配置文件中配置 <?x ...
- 170613、Spring整合RabbitMQ实例
一.rabbitMQ简介 1.1.rabbitMQ的优点(适用范围)1. 基于erlang语言开发具有高可用高并发的优点,适合集群服务器.2. 健壮.稳定.易用.跨平台.支持多种语言.文档齐全.3. ...
- Spring整合rabbitmq(转载)
原文地址:https://my.oschina.net/never/blog/140368 1.首先是生产者配置 <?xml version="1.0" encoding=& ...
- spring 整合rabbitMQ
<!-- 配置邮件消息队列监听 --> <bean id="maillistener" class="cn.xdf.wlyy.listener.Mail ...
- RabbitMQ的介绍与spring整合
本文主要讲述的是个人参考官网及其他前辈博客,对RabbitMQ的一些理解与spring整个RabbitMQ. 一.RabbitMQ的介绍 1.1.什么是RabbitMQ RabbitMQ是一个由erl ...
- spring boot实战(第十二篇)整合RabbitMQ
前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...
随机推荐
- nginx之rewrite相关功能
Nginx Rewrite相关功能 Nginx服务器利用ngx_http_rewrite_module 模块解析和处理rewrite请求,此功能依靠 PCRE(perl compatible regu ...
- java NIO面试题剖析
转载:https://mp.weixin.qq.com/s/YIcXaH7AWLJbPjnTUwnlyQ 首先我们分别画图来看看,BIO.NIO.AIO,分别是什么? BIO:传统的网络通讯模型,就是 ...
- 【Gamma】 Scrum Meeting 1
github 本此会议项目由PM召开,召开时间为5月26日晚上10点 召开时长20分钟 任务表格 姓名 当前任务 下阶段任务 袁勤 后端插入判断题 后端插入简答题 彭一夫 填空题答题前端 判断题答题前 ...
- 一个半吊子PM的反思
故事之源 2019年3月,也就是2016级计算机学院的大三时,软件工程这门课程由选修转为专业必修课,而七个葫芦娃共聚罗杰老师的课堂,组成葫芦娃不想写代码小分队.面临着继承往届项目.完成指定项目和自选项 ...
- SNPsnap | 筛选最佳匹配的SNP | 富集分析 | CP loci
一个矛盾: GWAS得到的SNP做富集分析的话,通常都会有强的偏向性. co-localization of GWAS signals to gene-dense and high linkage d ...
- pdf 中画虚线
<?php require('fpdf.php'); class PDF_Dash extends FPDF { function SetDash($black=null, $white=nul ...
- android ------ AndroidX的 Tablayout(com.google.android.material.tabs.TabLayout) 的使用
前面呢,有写过TabLayout的博客,最近开发用到了AndroidX来解决前面的问题,不要工具类设置下划线的问题了,来总结一下 Android--------TabLayout实现新闻客户端顶部导航 ...
- Ubuntu 上编译opencv_contrib模块for Android
https://blog.csdn.net/ipfpm/article/details/81132144 [ubuntu]Ubuntu中Android SDK下载跟配置 android24的版本 (1 ...
- fastreport 条形码 宽度问题
fastreport 的barcode 如果不设置AutoSize 确实可以控制宽度 但是生成后 基本没办法扫 所以换个思路 直接等比缩小 设置里面的zoom 比例为0.8 针对20位左右的条形码就 ...
- 转 zabbix 自动发现和 zabbix自定义用户key与参数User parameters
########31 https://www.cnblogs.com/yjt1993/p/10883345.html 1.概念 在配置Iterms的过程中,有时候需要对类似的Iterms进行添加,这些 ...