当前位置: 首页> 游戏> 游戏 > springboot集成RabbitMQ

springboot集成RabbitMQ

时间:2025/8/23 9:22:56来源:https://blog.csdn.net/qq_46517733/article/details/140862491 浏览次数:0次

springboot集成RabbitMQ

  • 1. 添加 Maven 依赖
  • 2. 配置 RabbitMQ
  • 3. 创建消息生产者
  • 4. 创建消息消费者
  • 5. 运行和测试

1. 添加 Maven 依赖

首先,你需要在你的 pom.xml 文件中添加 Spring Boot RabbitMQ Starter 的依赖。

<dependencies>  <dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-amqp</artifactId>  </dependency>    
</dependencies>

2. 配置 RabbitMQ

在 application.properties 或 application.yml 文件中添加 RabbitMQ 的配置信息。

spring.rabbitmq.host=localhost  
spring.rabbitmq.port=5672  
spring.rabbitmq.username=guest  
spring.rabbitmq.password=guest

3. 创建消息生产者

创建一个服务类来发送消息到 RabbitMQ 队列。

import org.springframework.amqp.rabbit.core.RabbitTemplate;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  @Service  
public class MessageProducerService {  @Autowired  private RabbitTemplate rabbitTemplate;  public void sendMessage(String queueName, String message) {  rabbitTemplate.convertAndSend(queueName, message);  }  
}

4. 创建消息消费者

创建一个类来监听 RabbitMQ 队列并处理接收到的消息。

import org.springframework.amqp.rabbit.annotation.RabbitListener;  
import org.springframework.stereotype.Component;  @Component  
public class MessageConsumerService {  @RabbitListener(queues = "myQueue")  public void receiveMessage(String message) {  System.out.println("Received message: " + message);  }  
}

5. 运行和测试

创建一个简单的 REST API 或使用 Spring Boot 的命令行运行器来测试 RabbitMQ 的集成。

import org.springframework.boot.CommandLineRunner;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.context.annotation.Bean;  @SpringBootApplication  
public class RabbitmqApplication {  public static void main(String[] args) {  SpringApplication.run(RabbitmqApplication.class, args);  }  @Bean  public CommandLineRunner run(MessageProducerService producer) {  return args -> {  producer.sendMessage("myQueue", "Hello RabbitMQ!");  };  }  
}
关键字:springboot集成RabbitMQ

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: