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博客

相关推荐
皮皮林5517 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904277 小时前
Spring Boot 用户管理系统
java·spring boot·后端
奔跑吧邓邓子7 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
茶本无香8 小时前
深入理解Spring Boot的EnvironmentPostProcessor:环境处理的黑科技
spring boot
奔跑吧邓邓子8 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE8 小时前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器
上官浩仁10 小时前
springboot redisson 缓存入门与实战
spring boot·redis·缓存
小小工匠10 小时前
SpringBoot - Spring 资源加载全解析:ResourceLoader 与 ResourceUtils 的正确打开方式
spring boot·spring·resourceloader·resourcutils
little_xianzhong12 小时前
关于对逾期提醒的定时任务~改进完善
java·数据库·spring boot·spring·mybatis
苹果醋312 小时前
数据库索引设计:在 MongoDB 中创建高效索引的策略
java·运维·spring boot·mysql·nginx