热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

springBoot整合rabbitMQ的方法详解

这篇文章主要介绍了springBoot整合rabbitMQ的方法详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

引入pom

<&#63;xml version="1.0" encoding="UTF-8"&#63;>

	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.4.5
		 
	
	com.wxy
	test-rabbitmq
	0.0.1-SNAPSHOT
	test-rabbitmq
	Demo project for Spring Boot
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-amqp
		
		
			org.springframework.boot
			spring-boot-starter-web
		
 
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework.amqp
			spring-rabbit-test
			test
		
        
            junit
            junit
            test
        
    
 
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	
 

测试

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 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 arguments
		amqpAdmin.declareBinding(new Binding("amqp.queue", Binding.DestinationType.QUEUE,
				"amqpexchange.direct","wxy.news", null));
 
	}

到此这篇关于springBoot整合rabbitMQ的方法详解的文章就介绍到这了,更多相关springBoot整合rabbitMQ内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 本文探讨了在通过 API 端点调用时,使用猫鼬(Mongoose)的 findOne 方法总是返回 null 的问题,并提供了详细的解决方案和建议。 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细记录了在基于Debian的Deepin 20操作系统上安装MySQL 5.7的具体步骤,包括软件包的选择、依赖项的处理及远程访问权限的配置。 ... [详细]
  • 探讨如何高效使用FastJSON进行JSON数据解析,特别是从复杂嵌套结构中提取特定字段值的方法。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 本文总结了在使用Ionic 5进行Android平台APK打包时遇到的问题,特别是针对QRScanner插件的改造。通过详细分析和提供具体的解决方法,帮助开发者顺利打包并优化应用性能。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • 本文详细介绍了如何在ECharts中使用线性渐变色,通过echarts.graphic.LinearGradient方法实现。文章不仅提供了完整的代码示例,还解释了各个参数的具体含义及其应用场景。 ... [详细]
  • Composer Registry Manager:PHP的源切换管理工具
    本文介绍了一个用于Composer的源切换管理工具——Composer Registry Manager。该项目旨在简化Composer包源的管理和切换,避免与常见的CRM系统混淆,并提供了详细的安装和使用指南。 ... [详细]
  • 本文详细介绍了Git分布式版本控制系统中远程仓库的概念和操作方法。通过具体案例,帮助读者更好地理解和掌握如何高效管理代码库。 ... [详细]
  • 探讨了小型企业在构建安全网络和软件时所面临的挑战和机遇。本文介绍了如何通过合理的方法和工具,确保小型企业能够有效提升其软件的安全性,从而保护客户数据并增强市场竞争力。 ... [详细]
  • 本文详细介绍了如何准备和安装 Eclipse 开发环境及其相关插件,包括 JDK、Tomcat、Struts 等组件的安装步骤及配置方法。 ... [详细]
  • 在本周的白板演练中,Apache Flink 的 PMC 成员及数据工匠首席技术官 Stephan Ewen 深入探讨了如何利用保存点功能进行流处理中的数据重新处理、错误修复、系统升级和 A/B 测试。本文将详细解释保存点的工作原理及其应用场景。 ... [详细]
  • 选择适合生产环境的Docker存储驱动
    本文旨在探讨如何在生产环境中选择合适的Docker存储驱动,并详细介绍不同Linux发行版下的配置方法。通过参考官方文档和兼容性矩阵,提供实用的操作指南。 ... [详细]
author-avatar
rseu_813
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有