SpringBoot集成rabbitMq

一、添加依赖:

pom.xml中添加Spring Boot的RabbitMQ依赖。

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

二、配置RabbitMQ:

application.propertiesapplication.yml中配置RabbitMQ连接信息。

XML 复制代码
# application.properties
spring.rabbitmq.host=local.rabbitmq.com
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
XML 复制代码
# application.yml
spring: 
  rabbitmq:
    host: local.rabbitmq.com
    port: 5672
    username: guest
    password: guest

三、创建配置类:

配置队列、交换器、路由等

java 复制代码
@Configuration
public class RabbitMqConfig {
    /**
      * 配置队列
      */
    @Bean
    Queue myQueue() {
        return new Queue("myQueue", true);
    }
    /**
      * 配置交换机
      */
    @Bean
    DirectExchange myExchange() {
        return new DirectExchange("myExchange");
    }
    /**
      * 队列和交换机绑定
      */
    @Bean
    Binding binding(Queue myQueue, DirectExchange myExchange) {
        return BindingBuilder.bind(myQueue).to(myExchange).with("myRoutingKey");
    }
}

四、发送和接收消息

使用RabbitTemplate发送消息,使用@RabbitListener注解接收消息。

java 复制代码
/**
 * 发送消息
 */
@Service
public class RabbitMqService {
 
    @Autowired
    private RabbitTemplate rabbitTemplate;
 
    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", message);
    }
}
java 复制代码
/**
 *接收消息
 */
@Component
public class RabbitMqReceiver {
 
    @RabbitListener(queues = "myQueue")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

确保你的RabbitMQ服务器正在运行,并且你的Spring Boot应用程序能够成功连接到它。这样你就可以通过RabbitMqService发送消息,并通过RabbitMqReceiver接收消息了。

参考链接:Springboot 整合RabbitMq ,用心看完这一篇就够了_springboot rabbitmq-CSDN博客

相关推荐
练习时长一年4 小时前
AopAutoConfiguration源码阅读
java·spring boot·intellij-idea
Q_Q196328847510 小时前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
悟纤12 小时前
Spring Boot 实用小技巧:多级缓存(Caffeine + Redis)- 第545篇
spring boot·后端·spring
MrSYJ13 小时前
UserDetailService是在什么环节生效的,为什么自定义之后就能被识别
java·spring boot·后端
Noii.15 小时前
Spring Boot初级概念及自动配置原理
java·spring boot·后端
勿在浮沙筑高台15 小时前
无法获取实体类com.example.springdemo2.entity.po.UserPO对应的表名!
java·spring boot·mybatis
掉头发的王富贵16 小时前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
DjangoJason1 天前
C++ 仿RabbitMQ实现消息队列项目
开发语言·c++·rabbitmq
杨DaB1 天前
【SpringBoot】Swagger 接口工具
java·spring boot·后端·restful·swagger
昵称为空C1 天前
SpringBoot接口限流的常用方案
服务器·spring boot