ToB企服应用市场:ToB评测及商务社交产业平台

标题: SpringBoot——整合RabbitMQ收发消息 [打印本页]

作者: 诗林    时间: 2024-8-19 07:39
标题: SpringBoot——整合RabbitMQ收发消息
目录
RabbitMQ消息队列 
项目总结
新建一个SpringBoot项目
pom.xml
application.properties配置文件
index.html前端页面
RabbitMQConfig配置类
RabbitMQProducer生产者
RabbitMQConsumer消费者
IndexController控制器
SpringbootRabbitmqApplication启动类
 测试


RabbitMQ消息队列 

   
  项目总结

     自己从填写要发送的信息的地方开始分析,顺藤摸瓜,将项目的几个文件串连起来
  新建一个SpringBoot项目


项目结构:

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.         <modelVersion>4.0.0</modelVersion>
  5.         <parent>
  6.                 <groupId>org.springframework.boot</groupId>
  7.                 <artifactId>spring-boot-starter-parent</artifactId>
  8.                 <version>2.3.12.RELEASE</version>
  9.                 <relativePath/> <!-- lookup parent from repository -->
  10.         </parent>
  11.         <groupId>com.study</groupId>
  12.         <artifactId>springboot_rabbitmq</artifactId>
  13.         <version>0.0.1-SNAPSHOT</version>
  14.         <name>springboot_rabbitmq</name>
  15.         <description>Demo project for Spring Boot</description>
  16.         <properties>
  17.                 <java.version>8</java.version>
  18.         </properties>
  19.         <dependencies>
  20.                 <dependency>
  21.                         <groupId>org.springframework.boot</groupId>
  22.                         <artifactId>spring-boot-starter-amqp</artifactId>
  23.                 </dependency>
  24.                 <dependency>
  25.                         <groupId>org.springframework.boot</groupId>
  26.                         <artifactId>spring-boot-starter-thymeleaf</artifactId>
  27.                 </dependency>
  28.                 <dependency>
  29.                         <groupId>org.springframework.boot</groupId>
  30.                         <artifactId>spring-boot-starter-web</artifactId>
  31.                 </dependency>
  32.                 <dependency>
  33.                         <groupId>org.springframework.boot</groupId>
  34.                         <artifactId>spring-boot-starter-test</artifactId>
  35.                         <scope>test</scope>
  36.                 </dependency>
  37.                 <dependency>
  38.                         <groupId>org.springframework.amqp</groupId>
  39.                         <artifactId>spring-rabbit-test</artifactId>
  40.                         <scope>test</scope>
  41.                 </dependency>
  42.         </dependencies>
  43.         <build>
  44.                 <plugins>
  45.                         <plugin>
  46.                                 <groupId>org.springframework.boot</groupId>
  47.                                 <artifactId>spring-boot-maven-plugin</artifactId>
  48.                         </plugin>
  49.                 </plugins>
  50.         </build>
  51. </project>
复制代码
application.properties配置文件

  1. spring.rabbitmq.host=192.168.40.128
  2. spring.rabbitmq.port=5672
  3. spring.rabbitmq.username=admin
  4. spring.rabbitmq.password=123456
  5. # 指定队列,交换机,路由键的名称
  6. #队列用于存储消息,生产者发送消息到队列,消费者从队列接收消息进行处理。
  7. rabbit.queue.name=springboot.queue.test
  8. #交换机负责将消息路由到一个或多个队列中,根据指定的路由键来确定消息的路由规则。
  9. rabbit.exchange.name=springboot.exchange.test
  10. #在消息发送时,会指定消息的路由键,交换机根据这个路由键来决定将消息路由到哪些队列中。
  11. rabbit.routing.key=springboot.routingkey.test
复制代码
index.html前端页面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Title</title>
  6. </head>
  7. <body>
  8.     <!--发送后,会触发IndexController的sendMessage方法-->
  9.     <form action="/sendMessage" method="post">
  10.         <!--在文本域填写要发送的消息-->
  11.         <textarea rows="4" cols="40" name="message"></textarea>
  12.         <!--点击"发送"按钮-->
  13.         <br><input type="submit" value="发送"/>
  14.     </form>
  15. </body>
  16. </html>
复制代码
RabbitMQConfig配置类

  1. package com.study.springboot_rabbitmq.config;
  2. import org.springframework.amqp.core.Binding;
  3. import org.springframework.amqp.core.BindingBuilder;
  4. import org.springframework.amqp.core.DirectExchange;
  5. import org.springframework.amqp.core.Queue;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. /**
  10. * 配置类: 绑定队列和交换器
  11. */
  12. @Configuration
  13. public class RabbitMQConfig {
  14.     @Value("${rabbit.queue.name}")
  15.     String queueName;
  16.     @Value("${rabbit.exchange.name}")
  17.     String exchangeName;
  18.     @Value("${rabbit.routing.key}")
  19.     String routingKey;
  20.     @Bean()
  21.     public Queue initQueue(){//创建队列
  22.         return new Queue(queueName);
  23.     }
  24.     @Bean()
  25.     public DirectExchange initDirectExchange(){//创建交换器
  26.         return new DirectExchange(exchangeName);
  27.     }
  28.     @Bean
  29.     public Binding bindingDirect(){//将队列与交换器绑定
  30.         return BindingBuilder.bind(initQueue()).to(initDirectExchange()).with(routingKey);
  31.     }
  32. }
复制代码
RabbitMQProducer生产者

  1. package com.study.springboot_rabbitmq.service;
  2. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.stereotype.Service;
  6. /**
  7. * 消息生产者
  8. */
  9. @Service
  10. public class RabbitMQProducer {
  11.     @Autowired
  12.     RabbitTemplate rabbitTemplate;
  13.     //读取配置文件中的交换器名称和路由键名称
  14.     @Value("${rabbit.exchange.name}")
  15.     String exchangeName;
  16.     @Value("${rabbit.routing.key}")
  17.     String routingKey;
  18.     //将消息发送给RabbitMQ的交换机,交换机通过路由键决定将消息路由到哪些队列
  19.     public void send(String message){
  20.         rabbitTemplate.convertAndSend(exchangeName,routingKey,message);
  21.     }
  22. }
复制代码
RabbitMQConsumer消费者

  1. package com.study.springboot_rabbitmq.service;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  5. import org.springframework.stereotype.Service;
  6. /**
  7. * 消息消费者
  8. */
  9. @Service
  10. public class RabbitMQConsumer {
  11.     private static final Logger log= LoggerFactory.getLogger(RabbitMQConsumer.class);
  12.     //使用@RabbitListener监听配置文件中的队列,当收到消息后,将其打印在控制台上
  13.     @RabbitListener(queues = "${rabbit.queue.name}")
  14.     public void getMessage(String message){
  15.         log.info("消费者收到消息:{}",message);
  16.     }
  17. }
复制代码
IndexController控制器

   
  1. package com.study.springboot_rabbitmq.config;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.amqp.core.*;
  5. import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
  6. import org.springframework.amqp.rabbit.connection.CorrelationData;
  7. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.cache.annotation.Caching;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. /**
  14. * 配置类: 绑定队列和交换器
  15. */
  16. @Configuration
  17. public class RabbitMQConfig {
  18.     private static final Logger log= LoggerFactory.getLogger(RabbitMQConfig.class);
  19.     @Autowired
  20.     private CachingConnectionFactory connectionFactory;
  21.     @Value("${rabbit.queue.name}")
  22.     String queueName;
  23.     @Value("${rabbit.exchange.name}")
  24.     String exchangeName;
  25.     @Value("${rabbit.routing.key}")
  26.     String routingKey;
  27.     @Bean()
  28.     public Queue initQueue(){//创建队列
  29.         return new Queue(queueName);
  30.     }
  31.     @Bean()
  32.     public DirectExchange initDirectExchange(){//创建交换器
  33.         return new DirectExchange(exchangeName);
  34.     }
  35.     @Bean
  36.     public Binding bindingDirect(){//将队列与交换器绑定
  37.         return BindingBuilder.bind(initQueue()).to(initDirectExchange()).with(routingKey);
  38.     }
  39.     //RabbitMQ收到消息后,把结果反馈给服务器,服务器将打印日志
  40.     @Bean
  41.     public RabbitTemplate rabbitTemplate(){
  42.         //消息发送成功后触发确认方法
  43.         connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
  44.         //消息发送失败后触发回调方法
  45.         connectionFactory.setPublisherReturns(true);
  46.         //通过连接工厂对象创建RabbitTemplate对象
  47.         RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
  48.         //若交换器无法匹配到指定队列,则取消发送消息
  49.         rabbitTemplate.setMandatory(true);
  50.         rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
  51.             @Override
  52.             public void confirm(CorrelationData correlationData, boolean ack, String cause) {//ack:RabbitMQ返回的应答
  53.                 if(ack){
  54.                     log.info("消息发送成功");
  55.                 }else{
  56.                     log.info("消息发送失败,原因: {}",cause);
  57.                 }
  58.             }
  59.         });
  60.         rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
  61.             @Override
  62.             public void returnedMessage(Message message, int i, String s, String s1, String s2) {
  63.                 log.info("消息发送失败: {}",message);
  64.             }
  65.         });
  66.         return rabbitTemplate;
  67.     }
  68. }
复制代码
SpringbootRabbitmqApplication启动类

  1. package com.study.springboot_rabbitmq;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SpringbootRabbitmqApplication {
  6.         public static void main(String[] args) {
  7.                 SpringApplication.run(SpringbootRabbitmqApplication.class, args);
  8.         }
  9. }
复制代码
 测试

开启RabbitMQ服务,启动项目
   从Spring Boot项目的角度来看,无论RabbitMQ运行在Windows还是Linux上,整合RabbitMQ的方式都是基本一致的,只要你的Spring Boot应用程序连接到RabbitMQ服务器,并使用RabbitMQ客户端库举行通讯即可
  





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4