RabbitMQ使用及与spring boot整合

2024-09-09 04:58

本文主要是介绍RabbitMQ使用及与spring boot整合,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.MQ

  消息队列(Message Queue,简称MQ)——应用程序和应用程序之间的通信方法

  应用:不同进程Process/线程Thread之间通信

  比较流行的中间件:

    ActiveMQ

    RabbitMQ(非常重量级,更适合于企业级的开发)

    Kafka(高吞吐量的分布式发布订阅消息系统)

    RocketMQ

  在高并发、可靠性、成熟度等方面,RabbitMQ是首选

  Kafka的性能(吞吐量、TPS)比RabbitMq要高出来很多,但Kafka主要定位在日志方面,如果业务方面还是建议选择RabbitMq

2.AMQP

  Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计

  主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全

3.RabbitMQ

RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写

支持多种客户端,如:Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP等,支持AJAX

用于在分布式系统中存储转发消息,在易用性、扩展性、高可用性等方面表现不俗

(1)安装

  需要先安装Erlang ,再安装RabbitMQ

  环境:win7

  Erlang

    下载 :

      https://www.erlang-solutions.com/resources/download.html 

    安装:

      双击下载的文件(esl-erlang_22.1~windows_amd64.exe) ,下一步进行安装

    安装完后开始菜单多了

      

  RabbitMQ

    下载 :

      https://www.rabbitmq.com/download.html

    安装:

      双击下载的文件(rabbitmq-server-3.8.1.exe) ,下一步进行安装

    安装完后开始菜单多了

      

     选择开始菜单的RabbitMQ Command Prompt(sbin dir)

     

    进入C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.4.1\sbin输入命令

rabbitmq-plugins enable rabbitmq_management

启动了管理工具

服务启动  net start RabbitMQ
服务停止  net stop RabbitMQ

服务启动后,浏览器打开http://localhost:15672/

使用账号 guest ,密码 guest

能够登录,安装成功

(2)用户管理

  Admin选项卡

  A.添加用户

用户角色:

    超级管理员(administrator)

    监控者(monitoring)

      策略制定者(policymaker)

    普通管理者(management)

    其他

  B.创建Virtual Hosts

   C.设置权限

   选中Admin用户,进入权限设置

 

   已添加权限

 (3)spring boot整合RabbitMQ

  添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId><version>2.2.1.RELEASE</version>
</dependency>

  添加配置

 

#对于rabbitMQ的支持
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=testhost
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true

 

  添加RabbitMQ配置类


package com.example.demo.configure;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMqConfig {public static final String RABBITMQ_QUEUE_NAME = "Queue1";public static final String RABBITMQ_ORDER_QUEUE_NAME = "OrderQueue1";private final static Logger logger = LoggerFactory.getLogger(RabbitMqConfig.class);@Autowiredprivate CachingConnectionFactory cachingConnectionFactory;@Beanpublic Queue commonQueue() {return new Queue(RabbitMqConfig.RABBITMQ_QUEUE_NAME);}@Beanpublic Queue orderQueue() {return new Queue(RabbitMqConfig.RABBITMQ_ORDER_QUEUE_NAME);}@Beanpublic DirectExchange directExchange() {return new DirectExchange("directExchange");}@Beanpublic TopicExchange topicExchange() {return new TopicExchange("topicExchange");}@Beanpublic FanoutExchange fanoutExchange() {return new FanoutExchange("fanoutExchange");}// 建立Queue与Exchange的绑定关系@Beanpublic Binding bindingExchangeMessage(Queue orderQueue, DirectExchange directExchange) {return BindingBuilder.bind(orderQueue).to(directExchange).with(RabbitMqConfig.RABBITMQ_ORDER_QUEUE_NAME);}@Beanpublic RabbitTemplate rabbitTemplate() {cachingConnectionFactory.setPublisherConfirms(true);cachingConnectionFactory.setPublisherReturns(true);RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);rabbitTemplate.setMandatory(true);rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {if (ack)logger.info("消息发送成功: correlationData:({}),ack:({ack}),cause:({})", correlationData,ack, cause);elselogger.info("消息发送失败: correlationData:({}),ack:({ack}),cause:({})", correlationData,ack, cause);});rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> logger.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange,routingKey, replyCode, replyText, message));return rabbitTemplate;}
}package

 

  生产者


package com.example.demo.mq;import com.example.demo.configure.RabbitMqConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class OrderMaker {private final static Logger logger = LoggerFactory.getLogger(OrderMaker.class);@Autowiredprivate RabbitTemplate rabbitTemplate;public void send(String content){this.rabbitTemplate.convertAndSend(RabbitMqConfig.RABBITMQ_ORDER_QUEUE_NAME,content);}
}package

 

  测试入口


package com.example.demo.controller;import com.example.demo.mq.OrderMaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
public class Demo {@Autowiredprivate OrderMaker orderMaker;@RequestMapping(value = "/testMq",method = RequestMethod.GET,produces = MediaType.ALL_VALUE)public String testMq(String msg){orderMaker.send(msg);System.out.println(msg);return "Successfully.";}
}package

 

  使用postman测试http://127.0.0.1:8080/testMq?msg=hahaha,this is a test

  在http://localhost:15672中

  OrderQueue1队列有两条消息

  查看消息

 

    消费者


package com.example.demo.mq;import com.example.demo.configure.RabbitMqConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
@RabbitListener(queues = RabbitMqConfig.RABBITMQ_ORDER_QUEUE_NAME)
public class OrderListener {private final static Logger logger = LoggerFactory.getLogger(OrderListener.class);@RabbitHandlerpublic void process(String orderMsg){logger.info("订单消费者收到消息:" + orderMsg);}
}package

 

  重新启动

  log输出

2019-11-13 14:36:51.500 [org.springframework.amqp.rabbit.RabbitListenerEndpointContainer#0-1] INFO  com.example.demo.mq.OrderListener - 订单消费者收到消息:hahaha,this is a test
2019-11-13 14:36:51.516 [AMQP Connection 127.0.0.1:5672] INFO  com.example.demo.configure.RabbitMqConfig - 消息发送成功: correlationData:(null),ack:({ack}),cause:(true)

这样就实现了简单的队列,生产者将消息发送到队列,消费者从队列中获取消息

P:消息的生产者
C:消息的消费者
红色:队列

 

这篇关于RabbitMQ使用及与spring boot整合的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1150219

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运