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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。