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

相关推荐
考虑考虑1 天前
Jpa使用union all
java·spring boot·后端
阿杆1 天前
同事嫌参数校验太丑,我直接掏出了更优雅的 SpEL Validator
java·spring boot·后端
昵称为空C2 天前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
往事随风去2 天前
架构师必备思维:从“任务队列”到“事件广播”,彻底吃透消息队列两大设计模式
消息队列·rabbitmq
麦兜*2 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*2 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
汤姆yu2 天前
基于springboot的毕业旅游一站式定制系统
spring boot·后端·旅游
计算机毕业设计木哥2 天前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计
hdsoft_huge3 天前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
AD钙奶-lalala3 天前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket