springboot+RabbitMQ发送和接收JSON数据

废话不多说,直接上代码

关于一些依赖和配置文件的设置请看前一期:https://www.cnblogs.com/wang-yaz/p/17619746.html

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

2.定义消息数据类,用于构建对象

 1 package com.example.rabbitmq_demo.rabbitmq;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * created by wyz on 2023/8/8
 7  *
 8  */
 9 public class MessageDto implements Serializable{
10     private String name = "张三";
11     private Integer age = 18;
12     private String sex = "";
13 
14     public MessageDto(String name, Integer age, String sex) {
15         this.name = name;
16         this.age = age;
17         this.sex = sex;
18     }
19 
20     public MessageDto() {
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public Integer getAge() {
32         return age;
33     }
34 
35     public void setAge(Integer age) {
36         this.age = age;
37     }
38 
39     public String getSex() {
40         return sex;
41     }
42 
43     public void setSex(String sex) {
44         this.sex = sex;
45     }
46 }

 3.创建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     public void sendMessage(String exchange,String routingKey, MessageDto dto){
22         //设置MessageId
23         String msgId = UUID.randomUUID().toString();
24 
25         MessageProperties messageProperties = new MessageProperties();
26         messageProperties.setMessageId(msgId);
27         messageProperties.setContentType("application/json");
28 
29         //创建Message
30         Message message = new Message(dto.toString().getBytes(StandardCharsets.UTF_8), messageProperties);
31         System.out.println("开始发送消息:" + dto);
32         rabbitTemplate.convertAndSend(exchange,routingKey,dto);
33         System.out.println("hahha");
34     }
35 }

4.创建消息监听类

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

5.创建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         rabbitMQService.sendMessage("weicang-test","ieou3356",new MessageDto("张三",20,""));
22     }
23 
24 }

6.运行程序后,跑接口,从日志看到已经发送成功和接受成功。

 

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