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

相关推荐
paopaokaka_luck2 分钟前
基于SpringBoot+Vue的电影售票系统(协同过滤算法)
vue.js·spring boot·后端
陌殇殇3 小时前
SpringBoot整合SpringCache缓存
spring boot·redis·缓存
小林学习编程6 小时前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
ladymorgana6 小时前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_10246 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
DCTANT7 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.7 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
喜欢敲代码的程序员9 小时前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis
Bug退退退1239 小时前
RabbitMQ 工作模式
java·分布式·rabbitmq
华子w90892585910 小时前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui