一文带你彻底搞懂SpringBoot-RabbitMQ(1),高级java工程师岗位职责

本文详细介绍了如何在SpringBoot中使用RabbitMQ实现消息接收者、发布订阅功能。讲解了声明交换器、队列、绑定,以及消息的发送与监听。内容涵盖topic、fanout、headers三种交换器类型,同时探讨了消息持久化的重要性及其实现方法。
摘要由CSDN通过智能技术生成

2.2.2 消息接收者

声明交换器、三个队列、队列的绑定

  • *:匹配一个串

  • #:匹配一个或者多个串

import org.springframework.amqp.core.Binding;

import org.springframework.amqp.core.BindingBuilder;

import org.springframework.amqp.core.Queue;

import org.springframework.amqp.core.TopicExchange;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration

public class BlogSubscriberConfig {

/**

  • 主题交换器

*/

@Bean

public TopicExchange blogTopicExchange() {

return ExchangeBuilder.topicExchange(“exchange.topic.springboot.blog”).build();

}

@Bean

public Queue blogJavaQueue() {

return QueueBuilder.durable(“queue.topic.springboot.blog.java”).build();

}

@Bean

public Queue blogMqQueue() {

return QueueBuilder.durable(“queue.topic.springboot.blog.mq”).build();

}

@Bean

public Queue blogAllQueue() {

return QueueBuilder.durable(“queue.topic.springboot.blog.all”).build();

}

@Bean

@Resource

public Binding blogJavaBinding(TopicExchange blogTopicExchange, Queue blogJavaQueue) {

return BindingBuilder.bind(blogJavaQueue).to(blogTopicExchange).with(“springboot.blog.java.routing.key”);

}

@Bean

@Resource

public Binding blogMqBinding(TopicExchange blogTopicExchange, Queue blogMqQueue) {

return BindingBuilder.bind(blogMqQueue).to(blogTopicExchange).with(“springboot.blog.mq.routing.key”);

}

@Bean

@Resource

public Binding blogAllBinding(TopicExchange blogTopicExchange, Queue blogAllQueue) {

// #: 匹配一个或者多个 *:匹配一个

return BindingBuilder.bind(blogAllQueue).to(blogTopicExchange).with(“springboot.blog.#.routing.key”);

}

}

复制代码

监听队列

import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.stereotype.Service;

@Service

public class BlogService {

/**

  • topic监听

*/

@RabbitListener(queues = “queue.topic.springboot.blog.java”)

public void blogJavaListener(String message) {

System.out.println("blogJavaListener message = " + message);

}

@RabbitListener(queues = “queue.topic.springboot.blog.mq”)

public void blogMqListener(String message) {

System.out.println("blogMqListener message = " + message);

}

@RabbitListener(queues = “queue.topic.springboot.blog.all”)

public void blogAllaListener(String message) {

System.out.println("blogAllListener message = " + message);

}

}

复制代码

2.2.3 消息发布订阅

  1. 发布者发送消息
  1. 订阅者收到消息
  • 全匹配和模糊匹配

  • 全匹配无论是哪个都会被匹配上

blogJavaListener message = hello

blogAllListener message = hello

blogAllListener message = hello

blogMqListener message = hello

复制代码

2.3 fanout - 广播交换器


2.3.1 消息发送者

声明fanout交换器

import org.springframework.amqp.core.FanoutExchange;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class NoticePublisherConfig {

@Bean

public Exchange radioFanoutExchange() {

return ExchangeBuilder.fanoutExchange(“exchange.fanout.springboot.radio”).build();

}

}

复制代码

声明controller

@RequestMapping("/fanout")

public Object fanout(String message) {

rabbitTemplate.convertAndSend(“exchange.fanout.springboot.radio”, null, message);

return message;

}

复制代码

2.32 消息接收者

创建交换器、路由键、绑定

  • 不需要使用路由键

import org.springframework.amqp.core.*;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration

public class NoticeSubscriberConfig {

@Bean

public FanoutExchange radioFanoutExchange() {

return ExchangeBuilder.fanoutExchange(“exchange.fanout.springboot.radio”).build();

}

@Bean

public Queue radioQueue() {

return QueueBuilder.durable(“queue.fanout.springboot.radio”).build();

}

@Bean

@Resource

public Binding radioBinding(FanoutExchange radioFanoutExchange, Queue radioQueue) {

// 广播交换器绑定没有路由键,只要绑定即可收到

return BindingBuilder.bind(radioQueue).to(radioFanoutExchange);

}

}

复制代码

监听队列

import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.stereotype.Service;

@Service

public class NoticeService {

@RabbitListener(queues = “queue.fanout.springboot.radio”)

public void radioListener(String message) {

System.out.println("radioListener message = " + message);

}

}

复制代码

2.3.3 消息发布订阅

发布者发送消息

订阅者收到消息

radioListener message = fanout

复制代码

2.4 headers - 头交换器


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 Spring Boot、RabbitMQ 和 WebSocket 结合的方式主要有以下几个步骤: 1. 创建 Spring Boot 项目,添加 RabbitMQ 和 WebSocket 的相关依赖。 2. 创建 RabbitMQ 队列和交换机,用于发送消息。 3. 创建 WebSocket 配置类,配置 WebSocket 的相关参数。 4. 创建 WebSocket 处理器类,处理 WebSocket 的连接、消息发送等操作。 5. 创建 RabbitMQ 消息监听器类,监听 RabbitMQ 队列中的消息,将消息发送给 WebSocket 处理器。 下面是具体的实现步骤: 1. 创建 Spring Boot 项目,添加 RabbitMQ 和 WebSocket 的相关依赖。 在 pom.xml 中添加以下依赖: ```xml <dependencies> <!-- RabbitMQ 相关依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <!-- WebSocket 相关依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies> ``` 2. 创建 RabbitMQ 队列和交换机,用于发送消息。 在 RabbitMQ 中创建一个交换机和一个队列,然后将队列绑定到交换机上。这里我们使用 RabbitMQ 的默认交换机和队列。 ```java @Configuration public class RabbitMQConfig { @Bean public Queue queue() { return new Queue("websocket"); } @Bean public DirectExchange exchange() { return new DirectExchange(""); } @Bean public Binding binding(Queue queue, DirectExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with("websocket"); } } ``` 3. 创建 WebSocket 配置类,配置 WebSocket 的相关参数。 ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); registry.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS(); } } ``` 4. 创建 WebSocket 处理器类,处理 WebSocket 的连接、消息发送等操作。 ```java @Component public class WebSocketHandler implements WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private SimpMessagingTemplate messagingTemplate; @Autowired public WebSocketHandler(SimpMessagingTemplate messagingTemplate) { this.messagingTemplate = messagingTemplate; } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.info("WebSocket connected: {}", session.getId()); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { logger.info("WebSocket received message: {}", message.getPayload()); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { logger.error("WebSocket transport error: {}", exception.getMessage()); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.info("WebSocket disconnected: {}", session.getId()); } @Override public boolean supportsPartialMessages() { return false; } public void sendMessage(String message) { messagingTemplate.convertAndSend("/topic/messages", message); } } ``` 5. 创建 RabbitMQ 消息监听器类,监听 RabbitMQ 队列中的消息,将消息发送给 WebSocket 处理器。 ```java @Component public class RabbitMQListener { private static final Logger logger = LoggerFactory.getLogger(RabbitMQListener.class); private WebSocketHandler webSocketHandler; @Autowired public RabbitMQListener(WebSocketHandler webSocketHandler) { this.webSocketHandler = webSocketHandler; } @RabbitListener(queues = "websocket") public void handleMessage(String message) { logger.info("RabbitMQ received message: {}", message); webSocketHandler.sendMessage(message); } } ``` 至此,Spring Boot、RabbitMQ 和 WebSocket 结合的实现就完成了。我们可以通过 RabbitMQ 发送消息到队列,然后监听器会将消息发送给 WebSocket 处理器,处理器再将消息发送给 WebSocket 客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值