• SpringBoot项目嵌入RabbitMQ


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


        org.springframework.boot
        spring-boot-starter-amqp

    然后,在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则会监听该队列,并处理接收到的消息。

  • 相关阅读:
    创建.gitignore文件并使用
    docker 下安装mysql8.0
    `算法知识` 算法代码模板
    python自动化测试selenium(三)下拉选择框、警告框处理、页面截图
    SpringCloud 微服务(二)
    _IO_2_1_stdin_ 任意写及对 _IO_2_1_stdout_ 任意读的补充
    这样做时间轴,让你的PPT更出彩!
    一文让你搞懂MYSQL底层原理。-内部结构、索引、锁、集群
    信奥中的数学:平面直角坐标系
    vscode的快捷键
  • 原文地址:https://blog.csdn.net/qq_41497074/article/details/136194343