RabbitMQ ③-Spring使用RabbitMQ

在这里插入图片描述

Spring使用RabbitMQ

创建 Spring 项目后,引入依赖:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置文件 application.yml

spring:application:name: spring-rabbitmq-demorabbitmq:
#    host: 47.94.9.33
#    port: 5672
#    username: admin
#    password: admin
#    virtual-host: /addresses: amqp://admin:admin@47.94.9.33:5672/

Work-Queue(工作队列模式)

声明队列

package com.ljh.mq.springrabbitmqdemo.config;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {// * 工作队列模式@Beanpublic Queue workQueue() {return QueueBuilder.durable(Constants.WORK_QUEUE).build();}
}

生产者

package com.ljh.mq.springrabbitmqdemo.controller;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/producer")
@RestController
public class ProducerController {private static final Logger log = LoggerFactory.getLogger(ProducerController.class);@AutowiredRabbitTemplate rabbitTemplate;@RequestMapping("/work")public String work() {for (int i = 0; i < 10; i++) {String msg = "hello work queue mode~ " + i;// ? 当使用默认交换机时,routingKey 和队列名称保持一致rabbitTemplate.convertAndSend("", Constants.WORK_QUEUE, msg);}log.info("消息发送成功");return "消息发送成功";}
}

消费者

package com.ljh.mq.springrabbitmqdemo.listener;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class WorkListener {private static final Logger log = LoggerFactory.getLogger(WorkListener.class);@RabbitListener(queues = Constants.WORK_QUEUE)public void process1(Message message, Channel channel) {log.info("[process1]:成功接收到消息:[{}]:{}", Constants.WORK_QUEUE, message);}@RabbitListener(queues = Constants.WORK_QUEUE)public void process2(String message) {log.info("[process2]:成功接收到消息:[{}]:{}", Constants.WORK_QUEUE, message);}
}

Publish/Subscribe(发布/订阅模式)

声明队列和交换机

package com.ljh.mq.springrabbitmqdemo.config;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {// * 发布订阅模式@Bean("fanoutExchange")public FanoutExchange fanoutExchange() {return ExchangeBuilder.fanoutExchange(Constants.FANOUT_EXCHANGE).durable(true).build();}@Bean("fanoutQueue1")public Queue fanoutQueue1 () {return QueueBuilder.durable(Constants.FANOUT_QUEUE1).build();}@Bean("fanoutQueue2")public Queue fanoutQueue2 () {return QueueBuilder.durable(Constants.FANOUT_QUEUE2).build();}@Bean("bindingFanout1")public Binding bindingFanout1(@Qualifier("fanoutExchange") FanoutExchange exchange, @Qualifier("fanoutQueue1") Queue queue) {return BindingBuilder.bind(queue).to(exchange);}@Bean("bindingFanout2")public Binding bindingFanout2(@Qualifier("fanoutExchange") FanoutExchange exchange, @Qualifier("fanoutQueue2") Queue queue) {return BindingBuilder.bind(queue).to(exchange);}
}

生产者

package com.ljh.mq.springrabbitmqdemo.controller;
package com.ljh.mq.springrabbitmqdemo.controller;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/producer")
@RestController
public class ProducerController {private static final Logger log = LoggerFactory.getLogger(ProducerController.class);@AutowiredRabbitTemplate rabbitTemplate;@RequestMapping("/fanout")public String fanout() {for (int i = 0; i < 10; i++) {String msg = "hello publish fanout mode~ " + i;// ? 当使用默认交换机时,routingKey 和队列名称保持一致rabbitTemplate.convertAndSend(Constants.FANOUT_EXCHANGE, "", msg);}log.info("消息发送成功");return "消息发送成功";}
}

消费者

package com.ljh.mq.springrabbitmqdemo.listener;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class FanoutListener {private static final Logger log = LoggerFactory.getLogger(FanoutListener.class);@RabbitListener(queues = Constants.FANOUT_QUEUE1)public void process1(String message) {log.info("[process1]:成功接收到消息:[{}]:{}", Constants.FANOUT_QUEUE1, message);}@RabbitListener(queues = Constants.FANOUT_QUEUE2)public void process2(String message) {log.info("[process2]:成功接收到消息:[{}]:{}", Constants.FANOUT_QUEUE2, message);}
}

Routing(路由模式)

声明队列和交换机

package com.ljh.mq.springrabbitmqdemo.config;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {// * 路由模式@Bean("directExchange")public DirectExchange directExchange() {return ExchangeBuilder.directExchange(Constants.DIRECT_EXCHANGE).durable(true).build();}@Bean("directQueue1")public Queue directQueue1() {return QueueBuilder.durable(Constants.DIRECT_QUEUE1).build();}@Bean("directQueue2")public Queue directQueue2() {return QueueBuilder.durable(Constants.DIRECT_QUEUE2).build();}@Bean("bindingDirect1")public Binding bindingDirect1(@Qualifier("directExchange") DirectExchange exchange, @Qualifier("directQueue1") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("orange");}@Bean("bindingDirect2")public Binding bindingDirect2(@Qualifier("directExchange") DirectExchange exchange, @Qualifier("directQueue2") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("orange");}@Bean("bindingDirect3")public Binding bindingDirect3(@Qualifier("directExchange") DirectExchange exchange, @Qualifier("directQueue2") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("black");}
}

生产者

package com.ljh.mq.springrabbitmqdemo.controller;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/producer")
@RestController
public class ProducerController {private static final Logger log = LoggerFactory.getLogger(ProducerController.class);@AutowiredRabbitTemplate rabbitTemplate;@RequestMapping("/direct/{routingKey}")public String direct(@PathVariable("routingKey") String routingKey) {rabbitTemplate.convertAndSend(Constants.DIRECT_EXCHANGE, routingKey, "hello routing mode~;routingKey is " + routingKey);log.info("消息发送成功:{}", routingKey);return "消息发送成功:" + routingKey;}
}

消费者

package com.ljh.mq.springrabbitmqdemo.listener;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class DirectListener {private static final Logger log = LoggerFactory.getLogger(DirectListener.class);@RabbitListener(queues = Constants.DIRECT_QUEUE1)public void process1(String message) {log.info("队列[{}]成功接收到消息:{}", Constants.DIRECT_QUEUE1, message);}@RabbitListener(queues = Constants.DIRECT_QUEUE2)public void process2(String message) {log.info("队列[{}]成功接收到消息:{}", Constants.DIRECT_QUEUE2, message);}
}

Topics(通配符模式)

声明队列和交换机

package com.ljh.mq.springrabbitmqdemo.config;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {// * 通配符模式@Bean("topicExchange")public TopicExchange topicExchange() {return ExchangeBuilder.topicExchange(Constants.TOPIC_EXCHANGE).durable(true).build();}@Bean("topicQueue1")public Queue topicQueue1() {return QueueBuilder.durable(Constants.TOPIC_QUEUE1).build();}@Bean("topicQueue2")public Queue topicQueue2() {return QueueBuilder.durable(Constants.TOPIC_QUEUE2).build();}@Bean("bindingTopic1")public Binding bindingTopic1(@Qualifier("topicExchange") TopicExchange exchange, @Qualifier("topicQueue1") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("*.orange.*");}@Bean("bindingTopic2")public Binding bindingTopic2(@Qualifier("topicExchange") TopicExchange exchange, @Qualifier("topicQueue2") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("*.*.rabbit");}@Bean("bindingTopic3")public Binding bindingTopic3(@Qualifier("topicExchange") TopicExchange exchange, @Qualifier("topicQueue2") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("lazy.#");}
}

生产者

package com.ljh.mq.springrabbitmqdemo.controller;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/producer")
@RestController
public class ProducerController {private static final Logger log = LoggerFactory.getLogger(ProducerController.class);@AutowiredRabbitTemplate rabbitTemplate;@RequestMapping("/topic/{routingKey}")public String topic(@PathVariable("routingKey") String routingKey) {rabbitTemplate.convertAndSend(Constants.TOPIC_EXCHANGE, routingKey, "hello topic mode~;routingKey is " + routingKey);log.info("消息发送成功:{}", routingKey);return "消息发送成功:" + routingKey;}
}

消费者

package com.ljh.mq.springrabbitmqdemo.listener;import com.ljh.mq.springrabbitmqdemo.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class TopicListener {private static final Logger log = LoggerFactory.getLogger(TopicListener.class);@RabbitListener(queues = Constants.TOPIC_QUEUE1)public void process1(String message) {log.info("队列[{}]成功接收到消息:{}", Constants.TOPIC_QUEUE1, message);}@RabbitListener(queues = Constants.TOPIC_QUEUE2)public void process2(String message) {log.info("队列[{}]成功接收到消息:{}", Constants.TOPIC_QUEUE2, message);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/905686.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

海外IP被误封解决方案

这里使用Google Cloud和Cloudflare来实现&#xff0c;解决海外服务器被误封IP&#xff0c;访问不到的问题。 这段脚本的核心目的&#xff0c;是自动监测你在 Cloudflare 上管理的 VPS 域名是否可达&#xff0c;一旦发现域名无法 Ping 通&#xff0c;就会帮你更换IP&#xff1a…

一个基于 Spring Boot 的实现,用于代理百度 AI 的 OCR 接口

一个基于 Spring Boot 的实现&#xff0c;用于代理百度 AI 的 OCR 接口 BaiduAIController.javaBaiduAIConfig.java在 application.yml 或 application.properties 中添加配置&#xff1a;application.yml同时&#xff0c;需要在Spring Boot应用中配置RestTemplate&#xff1a;…

GPT-4o 遇强敌?英伟达 Eagle 2.5 视觉 AI 王者登场

前言&#xff1a; 在人工智能领域&#xff0c;视觉语言模型的竞争愈发激烈。GPT-4o 一直是该领域的佼佼者&#xff0c;但英伟达的 Eagle 2.5 横空出世&#xff0c;凭借其 80 亿参数的精简架构&#xff0c;在长上下文多模态任务中表现出色&#xff0c;尤其是在视频和高分辨率图像…

将语言融入医学视觉识别与推理:一项综述|文献速递-深度学习医疗AI最新文献

Title 题目 Integrating language into medical visual recognition and reasoning: A survey 将语言融入医学视觉识别与推理&#xff1a;一项综述 01 文献速递介绍 检测以及语义分割&#xff09;是无数定量疾病评估和治疗规划的基石&#xff08;利特延斯等人&#xff0c…

Ubuntu24.04版本解决RK3568编译器 libmpfr.so.4: cannot open shared object

问题描述 在Ubuntu24.04版本上编译RK3568应用程序关于libmpfr.so.4: cannot open shared object问题&#xff0c;如下所示&#xff1a; /tools/ToolsChain/rockchip/rockchip_rk3568/host/bin/../libexec/gcc/aarch64-buildroot-linux-gnu/9.3.0/cc1plus: error while loadin…

产线视觉检测设备技术方案:基于EFISH-SCB-RK3588/SAIL-RK3588的国产化替代赛扬N100/N150全场景技术解析

一、核心硬件选型与替代优势‌ ‌1. 算力与AI加速能力‌ ‌异构八核架构‌&#xff1a;采用4Cortex-A76&#xff08;2.4GHz&#xff09;4Cortex-A55&#xff08;1.8GHz&#xff09;设计&#xff0c;支持视觉算法并行处理&#xff08;如模板匹配、缺陷分类&#xff09; 相机采…

python如何合并excel单元格

在Python中合并Excel单元格&#xff0c;常用openpyxl库实现。以下是详细步骤和示例代码&#xff1a; 方法一&#xff1a;使用 openpyxl 库 步骤说明&#xff1a; 安装库&#xff1a; pip install openpyxl导入库并加载文件&#xff1a; from openpyxl import load_workbook# …

高考备考1-集合

高考数学知识点总结—快手视频讲解 高考数学集合—快手视频讲解

Rust 数据结构:Vector

Rust 数据结构&#xff1a;Vector Rust 数据结构&#xff1a;Vector创建数组更新数组插入元素删除元素 获取数组中的元素迭代数组中的值使用枚举存储多个类型删除一个数组会删除它的元素 Rust 数据结构&#xff1a;Vector vector 来自标准库&#xff0c;在内存中连续存储相同类…

深度学习入门:深度学习(完结)

目录 1、加深网络1.1 向更深的网络出发1.2 进一步提高识别精度1.3 加深层的动机 2、深度学习的小历史2.1 ImageNet2.2 VGG2.3 GoogleNet2.4 ResNet 3、深度学习的高速化3.1 需要努力解决的问题3.2 基于GPU的高速化3.3 分布式学习3.4 运算精度的位数缩减 4、深度学习的应用案例4…

如何利用 Python 爬虫按关键字搜索京东商品:实战指南

在电商领域&#xff0c;京东作为国内知名的电商平台&#xff0c;拥有海量的商品数据。通过 Python 爬虫技术&#xff0c;我们可以高效地按关键字搜索京东商品&#xff0c;并获取其详细信息。这些信息对于市场分析、选品上架、库存管理和价格策略制定等方面具有重要价值。本文将…

‌JMeter聚合报告中的任务数和并发数区别

‌JMeter聚合报告中的任务数和并发数有本质的区别。‌ 任务数&#xff08;样本数&#xff09; 任务数或样本数是指在性能测试中发出的请求数量。例如&#xff0c;如果模拟20个用户&#xff0c;每个用户发送100次请求&#xff0c;那么总的任务数或样本数就是2000次请求‌ 并发…

Java 框架配置自动化:告别冗长的 XML 与 YAML 文件

在 Java 开发领域&#xff0c;框架的使用极大地提升了开发效率和系统的稳定性。然而&#xff0c;传统框架配置中冗长的 XML 与 YAML 文件&#xff0c;却成为开发者的一大困扰。这些配置文件不仅书写繁琐&#xff0c;容易出现语法错误&#xff0c;而且在项目规模扩大时&#xff…

OpenShift AI - 用 ModelCar 构建容器化模型,提升模型弹性扩展速度

《OpenShift / RHEL / DevSecOps 汇总目录》 说明&#xff1a;本文已经在 OpenShift 4.18 OpenShift AI 2.19 的环境中验证 文章目录 什么是 ModelCar构建模型镜像在 OpenShift AI 使用模型镜像部署模型扩展速度对比 参考 什么是 ModelCar KServe 典型的模型初始化方法是从 S…

C#+WPF+prism+materialdesign创建工具主界面框架

代码使用C#WPFprismmaterialdesign创建工具主界面框架 主界面截图&#xff1a;

在选择合适的实验室铁地板和铸铁试验平板,帮分析​

铸铁测试底板是一种采用铸铁材料经过加工制成的基准测量工具&#xff0c;主要用于工业检测、机械加工和实验室等高精度要求的场合。其核心功能是为各类测量、检验、装配工作提供稳定的水平基准面&#xff0c;确保测量数据的准确性和一致性。 一、铸铁测试底板的基本特性 1.材质…

C++匿名函数

C 中的匿名函数&#xff08;Lambda 表达式&#xff09;是 C11 引入的一项重要特性&#xff0c;它允许你在需要的地方定义一个临时的、无名的函数对象&#xff0c;使代码更加简洁和灵活。 1. 基本语法 Lambda 表达式的基本结构&#xff1a; [capture list](parameter list) -…

LabVIEW机械振动信号分析与故障诊断

利用 LabVIEW 开发机械振动信号分析与故障诊断系统&#xff0c;融合小波变换、时频分布、高阶统计量&#xff08;双谱&#xff09;等先进信号处理技术&#xff0c;实现对齿轮、发动机等机械部件的非平稳非高斯振动信号的特征提取与故障诊断。系统通过虚拟仪器技术将理论算法转化…

湖北理元理律师事务所:债务优化如何实现“减负不降质”?

在债务压力普遍加剧的背景下&#xff0c;如何平衡债务清偿与生活质量&#xff0c;成为个人及企业关注的焦点。湖北理元理律师事务所基于多年实务经验&#xff0c;总结出一套“法律财务”双轨制债务优化模型&#xff0c;其核心在于通过科学规划&#xff0c;帮助债务人在法律框架…

多链互操作性标准解析:构建下一代区块链互联生态

引言 在区块链技术快速演进的今天&#xff0c;“多链宇宙”已成为不可逆的趋势。然而&#xff0c;链与链之间的孤立性导致流动性割裂、开发成本高昂和用户体验碎片化。互操作性标准的制定&#xff0c;正是打破这一僵局的核心钥匙。本文将深入探讨主流互操作性协议的技术架构、…