springBoot整合rabbitMQ的方法详解
作者:喜羊羊love红太狼 发布时间:2022-08-19 02:28:33
标签:springBoot,整合,rabbitMQ
引入pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wxy</groupId>
<artifactId>test-rabbitmq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test-rabbitmq</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
测试
package com.wxy.rabbit;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
class TestRabbitmqApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void sendmessage() {
String exchange = "exchange.direct";
String routingkey = "wxy.news";
//object为消息发送的消息体,可以自动实现消息的序列化
Map<String,Object> msg = new HashMap<>();
msg.put("msg","使用mq发送消息");
msg.put("data", Arrays.asList("helloword",123456,true));
rabbitTemplate.convertAndSend(exchange, routingkey,msg);
}
@Test
public void receive() {
Object object = rabbitTemplate.receiveAndConvert("wxy.news");
System.out.println(object);
}
}
默认消息转换类型
###############在RabbitTemplate默认使用的是SimpleMessageConverter#######
private MessageConverter messageConverter = new SimpleMessageConverter();
###############源码:使用SerializationUtils.deserialize###############
public Object fromMessage(Message message) throws MessageConversionException {
Object content = null;
MessageProperties properties = message.getMessageProperties();
if (properties != null) {
String contentType = properties.getContentType();
if (contentType != null && contentType.startsWith("text")) {
String encoding = properties.getContentEncoding();
if (encoding == null) {
encoding = this.defaultCharset;
}
try {
content = new String(message.getBody(), encoding);
} catch (UnsupportedEncodingException var8) {
throw new MessageConversionException("failed to convert text-based Message content", var8);
}
} else if (contentType != null && contentType.equals("application/x-java-serialized-object")) {
try {
content = SerializationUtils.deserialize(this.createObjectInputStream(new ByteArrayInputStream(message.getBody()), this.codebaseUrl));
} catch (IllegalArgumentException | IllegalStateException | IOException var7) {
throw new MessageConversionException("failed to convert serialized Message content", var7);
}
}
}
将默认消息类型转化成自定义json格式
第一:上面SimpleMessageConverter是org.springframework.amqp.support.converter包下MessageConverter接口的一个实现类
第二:查看该接口MessageConverter下支持哪些消息转化
ctrl+H查看该接口中的所有实现类
第三步:找到json相关的convert
RabbitTemplateConfigurer中定义if (this.messageConverter != null)则使用配置的messageConverter
################## if (this.messageConverter != null)则使用配置的messageConverter
public void configure(RabbitTemplate template, ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
template.setConnectionFactory(connectionFactory);
if (this.messageConverter != null) {
template.setMessageConverter(this.messageConverter);
}
template.setMandatory(this.determineMandatoryFlag());
Template templateProperties = this.rabbitProperties.getTemplate();
if (templateProperties.getRetry().isEnabled()) {
template.setRetryTemplate((new RetryTemplateFactory(this.retryTemplateCustomizers)).createRetryTemplate(templateProperties.getRetry(), Target.SENDER));
}
templateProperties.getClass();
map.from(templateProperties::getReceiveTimeout).whenNonNull().as(Duration::toMillis).to(template::setReceiveTimeout);
templateProperties.getClass();
map.from(templateProperties::getReplyTimeout).whenNonNull().as(Duration::toMillis).to(template::setReplyTimeout);
templateProperties.getClass();
map.from(templateProperties::getExchange).to(template::setExchange);
templateProperties.getClass();
map.from(templateProperties::getRoutingKey).to(template::setRoutingKey);
templateProperties.getClass();
map.from(templateProperties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue);
}
配置一个messageConversert(org.springframework.amqp.support.converter包中的)
package com.wxy.rabbit.config;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MessageConverConfig {
@Bean
public MessageConverter getMessageConvert(){
return new Jackson2JsonMessageConverter();
}
}
再次发送消息体json格式
使用注解@RabbitListener监听
监听多个队列
@RabbitListener(queues = {"wxy.news","wxy.emps"})
监听单个队列
@RabbitListener(queues = "wxy.news")
package com.wxy.rabbit.service;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
@Service
public class RabbitMqReceiveService {
@RabbitListener(queues = {"wxy.news","wxy.emps"})
public void getReceiveMessage(){
System.out.println("监听到性的消息");
}
@RabbitListener(queues = {"wxy.news","wxy.emps"})
public void getReceiveMessageHead(Message message){
System.out.println(message.getBody());
System.out.println( message.getMessageProperties());
}
}
在程序中创建队列,交换器,并进行绑定
@Test
public void create() {
//创建一个点对点的交换器
amqpAdmin.declareExchange(new DirectExchange("amqpexchange.direct"));
//创建一个队列
// String name,:队列名称
// boolean durable :持久化
amqpAdmin.declareQueue(new Queue("amqp.queue",true));
//绑定
//String destination, Binding.DestinationType destinationType, String exchange, String routingKey
// @Nullable Map<String, Object> arguments
amqpAdmin.declareBinding(new Binding("amqp.queue", Binding.DestinationType.QUEUE,
"amqpexchange.direct","wxy.news", null));
}
来源:https://blog.csdn.net/qq_38423256/article/details/115770100


猜你喜欢
- 进阶JavaSE-三大接口:Comparator、Comparable和Cloneable。Comparable和Comparator这两个
- 一、简述最近接到一个新需求,让做一个动效进度条。由于我们的产品比较大,在软件启动的时候会消耗比较长的时间,原生的进度条已经不能满足我们的需求
- 【背景】spring-boot项目,打包成可执行jar,项目内有两个带有main方法的类并且都使用了@SpringBootApplicati
- 在项目开始之前,我的环境已配置完成,具体环境如何配置可参考网络教程。下面我们开始项目的实现库的导入#include<iostream&
- Settings -> Editor -> General -> Use soft wraps in editor&nbs
- 泛型代码可以让你写出根据自我需求定义、适用于任何类型的,灵活且可重用的函数和类型。它可以让你避免重复的代码,用一种清晰和抽象的方式来表达代码
- 前言P6Spy是一个框架,它可以无缝地拦截和记录数据库活动,而无需更改现有应用程序的代码。一般我们使用的比较多的是使用p6spy打印我们最后
- 方式1. 使用HashtableMap<String,Object> hashtable=new Hashtable
- 判断用户输入的是否至少含有N位小数。1.当用户输入的是非数字时抛出异常,返回false。2.当用户输入数字是,判断其数字是否至少含有N位小数
- 在 Intellij Idea 中,我们需要设置 Settings 中的 Java Compiler 和 Project Structure
- using System;using System.Collections.Generic;using System.ComponentMo
- spring的事务控制本质上是通过aop实现的。在springboot中使用时,可以通过注解@Transactional进行类或者方法级别的
- 本文实例为大家分享了Unity使用鼠标旋转物体效果的具体代码,供大家参考,具体内容如下了解完基础知识后,然我们来做个小程序练习一下1.在Ma
- java 设计模式之单例模式前言:在软件开发过程中常会有一些对象我们只需要一个,如:线程池(threadpool)、缓存(cac
- 注解注解定义Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。Java 语言中的类、方法、变
- 摘要 想必大家对小榕时光等扫描器都非常熟悉了,有没有自己写一个的冲动。最近微软推实施了.NET战略方案,C#是主推语言,你们是否
- 一、方法的定义1.方法体中最后返回值可以使用return, 如果使用了return, 那么方法体的返回值类型一定要指定2.如果方法体重没有r
- 制作透明窗体办法有好几种,各有优缺点. 我们先来看看C#本身提供的办法 1:通过设置窗体的 TransparencyKey实现 例:窗体中
- 示例代码如下:launch(Dispatchers.Main) { // 第一部分 fl
- 在项目里,我需要做一个Spring Boot结合Thymeleaf前端模版,结合JPA实现分页的演示效果。做的时候发现有些问题,也查了现有网