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

相关推荐
武子康32 分钟前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
G_whang5 小时前
jenkins使用Jenkinsfile部署springboot+docker项目
spring boot·docker·jenkins
hac13229 小时前
Spring Boot 双数据源配置
java·spring boot·后端
凤山老林10 小时前
Spring Boot中的中介者模式:终结对象交互的“蜘蛛网”困境
java·spring boot·后端·设计模式·中介者模式
沃夫上校11 小时前
Spring Boot 中使用 Redis
spring boot·redis
java_强哥12 小时前
Spring Boot启动原理:从main方法到内嵌Tomcat的全过程
spring boot·后端·tomcat
李剑一12 小时前
上传三个参数,两个接收正常,一个死活都是null?
spring boot·后端
泉城老铁13 小时前
Spring Boot深度整合RabbitMQ:从入门到企业级实战
java·后端·rabbitmq
想要成为祖国的花朵14 小时前
Java_Springboot技术框架讲解部分(二)
java·开发语言·spring boot·spring
Q_Q51100828514 小时前
python的小学课外综合管理系统
开发语言·spring boot·python·django·flask·node.js