Python 官方文档:入门教程 => 点击学习
目录一.前言1.1场景1.2消息交换机三种形式二.建设demo工程2.1依赖2.2yml文件指定RabbitMQ连接信息2.3直连型消息链接一.前言 1.1场景 在我们实际开发中到一
在我们实际开发中到一个特定的时候是比如工作流到某个状态时, 我们会向某某单位发送消息, 这时就会用到我们的消息推送---rabbitMQ
简单画一下:
首先我们了解下消息队列是由交换机exchange和队列组合构成的,有三种形式
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-WEB</artifactId>
</dependency>
server:
port: 8021
spring:
#给项目来个名字
application:
name: rabbitmq-provider
#配置rabbitMq 服务器
rabbitmq:
host: localhost
port: 5672
#确认消息已发送到交换机(Exchange)
publisher-confirm-type: correlated
#确认消息已发送到队列(Queue)
publisher-returns: true
注意:我们需要创建两个工程,一个生产者producer
、一个消费者comsumer
,生产者用来生产消息,消费者用来消费生产者将消息投递到rabbitmq中的消息。
两个工程中的pom依赖一样,yml也一样,只需要将server.port
设置成不同的端口即可。这里我们将生产者设置为8021
端口,消费者设置为8022
端口。
从上面的讲解中我们知道,有交换机exchange
,有队列queue
,有路由routing
,因此我们需要在生产者端将三者关联起来,然后发送消息,这样消费端才能收到消息。
创建config工作类绑定关联
@Configuration
public class Config {
public static String directRouting = "directRouting";
public static String directQueue = "directQueue";
public static String directExchange = "directExchange";
@Bean
public Queue DirectQueue() {
return new Queue(Config.directQueue,true); //true 是否持久
}
@Bean
DirectExchange DirectExchange() {
return new DirectExchange(Config.directExchange);
}
@Bean
Binding bindingDirect() {
// BindingBuilder.bind(队列A).to(交换机B).with(路由) 将队列A绑定到交换机B,使用路由C传递消息
return BindingBuilder.bind(DirectQueue()).to(DirectExchange()).with(directRouting);
}
发送消息
@Autowired
private RabbitTemplate rabbitTemplate; //使用RabbitTemplate,这提供了接收/发送等等方法
@GetMapping("/sendDirectMsg")
public String sendMsg() {
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",UUID.randomUUID().toString());
map.put("data","hello,i am direct msg!");
map.put("datetime",System.currentTimeMillis());
//交换机 路由 消息(发送消息的时候不需要管队列,因为队列已经在DirectRabbitConfig中配置了,队列应该是消费者关心的事情)
rabbitTemplate.convertAndSend(DirectRabbitConfig.directExchange, DirectRabbitConfig.directRouting, map);
return "ok";
}
第二个工程中: 接收消息
@Component
@RabbitListener(queues = "directQueue")//监听的队列名称 directQueue,不需要管路由和交换机,因为这些是生产者管理的事情。消费者只需要关心队列即可
public class DirectReceiver {
@RabbitHandler
public void handler(Map testMessage) {
System.out.println("directReceiver消费者收到消息 : " + testMessage.toString());
}
}
到此这篇关于Rabbitmq消息推送功能实现示例的文章就介绍到这了,更多相关Rabbitmq消息推送内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Rabbitmq消息推送功能实现示例
本文链接: https://www.lsjlt.com/news/175921.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0