SpringBoot项目嵌入RabbitMQ

在Spring Boot中嵌入RabbitMQ可以通过添加相应的依赖来完成。首先需要在pom.xml文件中引入spring-boot-starter-amqp依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

然后,在application.properties或者application.yml配置文件中设置RabbitMQ连接信息:

spring.rabbitmq.host=your_rabbitmq_hostname

spring.rabbitmq.port=5672

spring.rabbitmq.username=your_rabbitmq_username

spring.rabbitmq.password=your_rabbitmq_password

最后,创建消息发送者(Producer)和消息接收者(Consumer)类,并使用@Autowired注解将其自动装载到Spring容器中。示例如下:

  1. 创建消息发送者类:

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
 
@Component
public class MessageSender {
    
    @Autowired
    private ApplicationContext context;
    
    public void send(String message) {
        Queue queue = (Queue) context.getBean("myQueue"); // 获取队列对象
        
        MessageChannel channel = context.getBean(queue.getName(), MessageChannel.class); // 根据队列名称获取消息通道
        
        channel.send(MessageBuilder.withPayload(message).build()); // 发送消息
    }
}

  1. 创建消息接收者类:

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
 
@Component
public class MessageReceiver {
    
    @RabbitListener(queues = "myQueue") // 指定监听的队列名称
    public void receive(String message) {
        System.out.println("Received message: " + message);
    }
}

 当调用MessageSendersend()方法时,会向"myQueue"队列发送消息;

MessageReceiver则会监听该队列,并处理接收到的消息。

相关推荐

  1. SpringBoot项目嵌入RabbitMQ

    2024-02-21 08:18:05       21 阅读
  2. SpringBoot 整合 RabbitMQ

    2024-02-21 08:18:05       34 阅读
  3. springboot整合RabbitMQ

    2024-02-21 08:18:05       28 阅读
  4. Springboot集成Rabbitmq

    2024-02-21 08:18:05       16 阅读
  5. SpringBoot集成RabbitMQ

    2024-02-21 08:18:05       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-21 08:18:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-21 08:18:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-21 08:18:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-21 08:18:05       18 阅读

热门阅读

  1. 过滤器:Gateway GlobalFilter在分布式系统中的应用

    2024-02-21 08:18:05       31 阅读
  2. 给图片添加

    2024-02-21 08:18:05       24 阅读
  3. 按身高和体重排队,运动会(C 语言)

    2024-02-21 08:18:05       28 阅读
  4. 寄存器 Flip-Flop

    2024-02-21 08:18:05       20 阅读
  5. 拍立淘助力电商新趋势:以图搜图购物成主流

    2024-02-21 08:18:05       30 阅读
  6. LeetCode 56 合并区间

    2024-02-21 08:18:05       31 阅读