当前位置: 首页 > news >正文

Spring_AMQP

文章目录

  • 一、SpringAMQP
  • 二、SpringAMQP应用
    • 2.1、消息发送
    • 2.2、消息接收

一、SpringAMQP

  SpringAMQP是基于RabbitMQ封装的一套模板,并且还利用SpringBoot对其实现了自动装配,使用起来非常方便。

  SpringAmqp的官方地址。
在这里插入图片描述
在这里插入图片描述
 
SpringAMQP提供了三个功能:

  • 自动声明队列、交换机及其绑定关系
  • 基于注解的监听器模式,异步接收消息
  • 封装了RabbitTemplate工具,用于发送消息

二、SpringAMQP应用

在父工程中引入依赖:

<!--AMQP依赖,包含RabbitMQ-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.1、消息发送

首先配置MQ地址,在publisher服务的application.yml中添加配置:

spring:rabbitmq:host: 192.168.150.101 # 主机名port: 5672 # 端口virtual-host: / # 虚拟主机username: itcast # 用户名password: 123321 # 密码

然后在publisher服务中编写测试类SpringAmqpTest,并利用RabbitTemplate实现消息发送:

package cn.itcast.mq.spring;import org.junit.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;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSimpleQueue() {// 队列名称String queueName = "simple.queue";// 消息String message = "hello, spring amqp!";// 发送消息rabbitTemplate.convertAndSend(queueName, message);}
}

2.2、消息接收

首先配置MQ地址,在consumer服务的application.yml中添加配置:

spring:rabbitmq:host: 192.168.150.101 # 主机名port: 5672 # 端口virtual-host: / # 虚拟主机username: itcast # 用户名password: 123321 # 密码

然后在consumer服务的包中新建一个类SpringRabbitListener,代码如下:

package cn.itcast.mq.listener;import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class SpringRabbitListener {@RabbitListener(queues = "simple.queue")public void listenSimpleQueueMessage(String msg) throws InterruptedException {System.out.println("spring 消费者接收到消息:【" + msg + "】");}
}

http://www.mrgr.cn/news/33393.html

相关文章:

  • Linux:进程(四)
  • 内核是如何发送数据包
  • 文档布局内容检测系统源码分享
  • 连续数组问题
  • STL之list
  • c语言-数据类型
  • C++:数组与字符串
  • Git从了解到操作
  • 【homebrew安装】踩坑爬坑教程
  • Renesas R7FA8D1BH (Cortex®-M85) 生成4路PWM
  • 【ArcGIS微课1000例】0123:数据库中要素类批量转为shapefile
  • 数据结构之堆(优先级队列)
  • 2024/9/22周报
  • 【面经】查找中常见的树数据结构
  • 8. Data Member的绑定
  • 国产游戏技术能否引领全球【终稿】
  • CompletableFuture如何优雅处理异步任务超时!妙就完了
  • 国人卖家可折叠无线充电器发起TRO专利维权,功能相同可能侵权
  • 【深入学习Redis丨第六篇】Redis哨兵模式与操作详解
  • 图神经网络的新篇章:通用、强大、可扩展的图变换器