springboot+RabbitMQ发送和接收字符串数据

我采用的是阿里云“消息队列RabbitMQ版”, 具体操作请到阿里云后台查看,

链接是如何创建exchange,queue以及绑定关系

https://help.aliyun.com/document_detail/101900.html?spm=a2c4g.102246.0.0.7d0c675dxkMJoI

下面是基于以上资源都创建好的情况下实现的。

1.在pom.xml文件中添加以下依赖

 1    <dependency>
 2             <groupId>com.rabbitmq</groupId>
 3             <artifactId>amqp-client</artifactId>
 4             <version>5.5.0</version> <!-- 支持开源所有版本 -->
 5         </dependency>
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-amqp</artifactId>
 9         </dependency>
10         <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
11         <dependency>
12             <groupId>com.alibaba.fastjson2</groupId>
13             <artifactId>fastjson2</artifactId>
14             <version>2.0.26</version>
15         </dependency>

2.在配置文件application.properties

 1 server.port=8080
 2 spring.profiles.active=dev
 3 
 4 #实例的接入点
 5 spring.rabbitmq.host=xxxxxxxxx-ai-a.aliyuncs.com   //更换为自己阿里云RabbitMQ接入点
 6 spring.rabbitmq.port=5672
 7 spring.rabbitmq.username=xxxxxxx---xcUc=          //静态用户名和密码(已提前创建好)
 8 spring.rabbitmq.password=xxxxx--NjkxMDQzMDIzMzM5
 9 
10 #虚拟主机
11 spring.rabbitmq.virtual-host=ieou   //更换为自己的vhost
12 #消费消息时,消息手动确认
13 spring.rabbitmq.listener.simple.acknowledge-mode=manual
14 #不创建AmqpAdmin bean
15 spring.rabbitmq.dynamic=false

 3.创建RabbitMQConfig配置类

 1 package com.example.rabbitmq_demo.rabbitmq;
 2 
 3 import org.springframework.amqp.core.AcknowledgeMode;
 4 import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
 5 import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
 6 import org.springframework.amqp.rabbit.connection.ConnectionFactory;
 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.boot.autoconfigure.condition.ConditionalOnClass;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.context.annotation.Configuration;
13 
14 /**
15  * created by wyz on 2023/8/8
16  */
17 @Configuration
18 public class RabbitMQConfig {
19 
20     @Value("${spring.rabbitmq.host}")
21     private String host;
22 
23     @Value("${spring.rabbitmq.port}")
24     private int port;
25 
26     @Value("${spring.rabbitmq.username}")
27     private String username;
28 
29     @Value("${spring.rabbitmq.password}")
30     private String password;
31 
32     @Value("${spring.rabbitmq.virtual-host}")
33     private String virtualHost;
34 
35     @Autowired
36     RabbitTemplate rabbitTemplate;
37 
38     @Bean
39     public ConnectionFactory connectionFactory(){
40         //初始化RabbitMQ连接配置connectionFactory
41         CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
42 
43         connectionFactory.setHost(host);
44         connectionFactory.setPort(port);
45         connectionFactory.setUsername(username);
46         connectionFactory.setPassword(password);
47         connectionFactory.setVirtualHost(virtualHost);
48         //请务必开启Connection自动重连功能,保证服务端发布时客户端可自动重新连接上服务端
49         connectionFactory.getRabbitConnectionFactory().setAutomaticRecoveryEnabled(true);
50         //设置缓存模式为CONNECTION
51         connectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CONNECTION);
52         //Connection模式下,最大可缓存的connection数量
53         connectionFactory.setConnectionCacheSize(10);
54         //Connection模式下,最大可缓存的channel数量
55         connectionFactory.setChannelCacheSize(64);
56 
57         return connectionFactory;
58 
59     }
60 
61     @Bean
62     @ConditionalOnClass
63     public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(CachingConnectionFactory cachingConnectionFactory){
64         SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
65         factory.setConnectionFactory(cachingConnectionFactory);
66         factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
67         return factory;
68     }
69 
70     @Bean
71     public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
72         //RabbitMQ消息模板,该模板封装了多种常用的消息操作
73         return new RabbitTemplate(connectionFactory);
74     }
75 
76 }

4.创建RabbitMQService发送服务类

 1 package com.example.rabbitmq_demo.rabbitmq;
 2 
 3 import org.springframework.amqp.core.Message;
 4 import org.springframework.amqp.core.MessageProperties;
 5 import org.springframework.amqp.rabbit.connection.CorrelationData;
 6 import org.springframework.amqp.rabbit.core.RabbitTemplate;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 
10 import java.nio.charset.StandardCharsets;
11 import java.util.UUID;
12 
13 /**
14  * created by wyz on 2023/8/8
15  */
16 @Service
17 public class RabbitMQService {
18 
19     @Autowired
20     private RabbitTemplate rabbitTemplate;
21 
22 
23     public void sendMessage(String exchange,String routingKey, String content){
24         //设置MessageId
25         String msgId = UUID.randomUUID().toString();
26 
27         MessageProperties messageProperties = new MessageProperties();
28         messageProperties.setMessageId(msgId);
29         messageProperties.setContentType("application/json");
30 
31         //创建Message
32         Message message = new Message(content.getBytes(StandardCharsets.UTF_8), messageProperties);
33         System.out.println("开始发送消息:" + content);
34         rabbitTemplate.convertAndSend(exchange,routingKey,message);
35         System.out.println("消息发送成功:" + content);
36     }
37 
38 }

5.创建消息监听类

 1 package com.example.rabbitmq_demo.rabbitmq;
 2 
 3 
 4 import com.rabbitmq.client.Channel;
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 import org.springframework.amqp.core.Message;
 8 import org.springframework.amqp.rabbit.annotation.RabbitListener;
 9 import org.springframework.amqp.support.AmqpHeaders;
10 import org.springframework.messaging.handler.annotation.Header;
11 import org.springframework.stereotype.Component;
12 
13 import java.io.IOException;
14 
15 
16 /**
17  * created by wyz on 2023/8/8
18  */
19 @Component
20 public class MessageListener {
21 
22     private static final Logger log = LoggerFactory.getLogger(MessageListener.class);
23 
24 
25     /**
26      * 消息接收 手动确认ack
27      * @param
28      * @param deliveryTag
29      * @param channel
30      * @throws
31      */
32     @RabbitListener(queues = "weicang")
33     public void receiveFromMyQueue(Message message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
34         String s = new String(message.getBody());
35         log.info("receive message: {}", s + "msgId:" + message.getMessageProperties().getMessageId());
36         // 进入消息消费业务逻辑。
37         System.out.println("收到消息:" + s);
38 
39         // 在1分钟内,返回ack,否则为无效确认,消息还会被重复投递。
40         channel.basicAck(deliveryTag,false);
41     }
42 
43 }

6.创建controller类,写一个接口用于调用发送消息方法

 1 package com.example.rabbitmq_demo.rabbitmq;
 2 
 3 
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.web.bind.annotation.GetMapping;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 /**
10  * created by wyz on 2023/8/8
11  */
12 @RestController
13 @RequestMapping(produces = "application/json;charset=UTF-8")
14 public class TestSenderController {
15 
16     @Autowired
17     private RabbitMQService rabbitMQService;
18 
19     @GetMapping("/send")
20     public void send() {
21         // 这里要换成自己的exchange和routingKey
22         rabbitMQService.sendMessage("weicang-test","ieou3356","这是一条消息");
23     }
24 }

7.运行程序后,跑接口,从日志看到已经发送成功和接受成功。  下一期讲下怎么发送和接收JSON格式数据

 

posted @ 2023-08-10 11:24  低调的小白  阅读(458)  评论(0编辑  收藏  举报