文章目录
- 7.RabbitMQ实现JSON、Map格式数据的发送与接收
- 7.1消息发送端
- 7.1.1引入依赖
- 7.1.2yml配置
- 7.1.3RabbitMQConfig配置类——(非常重要)
- (1)创建交换器方法
- (2)创建队列方法
- (3)绑定方法
- (4)创建死信交换器、死信队列、绑定关系
- (5)发送消息方(立即发送JSON格式数据/延迟发送Map格式数据)
- ①实体类
- ②service层
- ③serviceImpl类
- 7.2消息接收端
- 7.2.1引入依赖
- 7.2.2yml配置
- 7.2.3RabbitMQConfig配置类——(非常重要)
- 7.2.4统一消息处理类——AckReceiver
- 7.2.5接收消息
- (1)接收JSON数据
- (2)接收map数据
- 7.3总结
7.RabbitMQ实现JSON、Map格式数据的发送与接收
在实现的项目开发中,经常使用Json、Map格式数据。下面将介绍RabbitMQ实现Json、Map格式数据的发送与接收。
7.1消息发送端
在消息发送端服务引入依赖、yml配置、RabbitMQ配置类、消息发送类
7.1.1引入依赖
<!-- AMQP客户端 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
7.1.2yml配置
spring:application:name: rabbitmq-providerrabbitmq:host: 127.0.0.1port: 5672username: guestpassword: guestpublisher-confirm-type: correlated publisher-returns: true
7.1.3RabbitMQConfig配置类——(非常重要)
在项目中,创建配置类,配置 消息确认,Json转换器,队列名称 等,并将队列交由 IoC 管理。代码如下:
package com.pjb.config;import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.HashMap;
import java.util.Map;/*** RabbitMQ配置类**/
@Configuration
public class RabbitMqConfig
{public static final String DIRECT_QUEUE = "direct_queue"; //Direct队列名称public static final String DIRECT_EXCHANGE = "direct_exchange"; //交换器名称public static final String DIRECT_ROUTING_KEY = "direct_routing_key"; //路由键public static final String DELAY_QUEUE = "delay_queue"; //延时队列名称public static final String DELAY_EXCHANGE = "delay_exchange"; //交换器名称public static final String DELAY_ROUTING_KEY = "delay_routing_key"; //路由键@Autowiredprivate CachingConnectionFactory connectionFactory;@Beanpublic RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){RabbitTemplate rabbitTemplate = new RabbitTemplate();rabbitTemplate.setConnectionFactory(connectionFactory);//设置Json转换器rabbitTemplate.setMessageConverter(jsonMessageConverter());//设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数rabbitTemplate.setMandatory(true);//确认消息送到交换机(Exchange)回调rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback(){@Overridepublic void confirm(CorrelationData correlationData, boolean ack, String cause){System.out.println("\n确认消息送到交换机(Exchange)结果:");System.out.println("相关数据:" + correlationData);System.out.println("是否成功:" + ack);System.out.println("错误原因:" + cause);}});//确认消息送到队列(Queue)回调rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback(){@Overridepublic void returnedMessage(ReturnedMessage returnedMessage){System.out.println("\n确认消息送到队列(Queue)结果:");System.out.println("发生消息:" + returnedMessage.getMessage());System.out.println("回应码:" + returnedMessage.getReplyCode());System.out.println("回应信息:" + returnedMessage.getReplyText());System.out.println("交换机:" + returnedMessage.getExchange());System.out.println("路由键:" + returnedMessage.getRoutingKey());}});return rabbitTemplate;}/*** Json转换器*/@Beanpublic Jackson2JsonMessageConverter jsonMessageConverter(){return new Jackson2JsonMessageConverter();}/*** Direct交换器*/@Beanpublic DirectExchange directExchange(){return new DirectExchange(DIRECT_EXCHANGE, true, false);}/*** 队列*/@Beanpublic Queue directQueue(){return new Queue(DIRECT_QUEUE, true, false, false, null);}/*** 绑定*/@BeanBinding directBinding(DirectExchange directExchange, Queue directQueue){//将队列和交换机绑定, 并设置用于匹配键:routingKey路由键return BindingBuilder.bind(directQueue).to(directExchange).with(DIRECT_ROUTING_KEY);}/******************************延时队列******************************/@Beanpublic CustomExchange delayExchange(){Map<String, Object> args = new HashMap<>();args.put("x-delayed-type", "direct");return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, args);}@Beanpublic Queue delayQueue(){Queue queue = new Queue(DELAY_QUEUE, true);return queue;}@Beanpublic Binding delaybinding(Queue delayQueue, CustomExchange delayExchange){return BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAY_ROUTING_KEY).noargs();}
}
下面将讲述创建交换器、创建队列、将交换器和队列进行绑定各种方法
(1)创建交换器方法
/*** Direct交换器*/@Beanpublic DirectExchange directExchange(){/*** 创建交换器,参数说明:* String name:交换器名称* boolean durable:设置是否持久化,默认是 false。durable 设置为 true 表示持久化,反之是非持久化。* 持久化可以将交换器存盘,在服务器重启的时候不会丢失相关信息。* boolean autoDelete:设置是否自动删除,为 true 则设置队列为自动删除,*/return new DirectExchange(DIRECT_EXCHANGE, true, false);}
(2)创建队列方法
/*** 队列*/@Beanpublic Queue directQueue(){/*** 创建队列,参数说明:* String name:队列名称。* boolean durable:设置是否持久化,默认是 false。durable 设置为 true 表示持久化,反之是非持久化。* 持久化的队列会存盘,在服务器重启的时候不会丢失相关信息。* boolean exclusive:设置是否排他,默认也是 false。为 true 则设置队列为排他。* boolean autoDelete:设置是否自动删除,为 true 则设置队列为自动删除,* 当没有生产者或者消费者使用此队列,该队列会自动删除。* Map<String, Object> arguments:设置队列的其他一些参数。*/return new Queue(DIRECT_QUEUE, true, false, false, null);}
(3)绑定方法
/*** 绑定*/@BeanBinding directBinding(DirectExchange directExchange, Queue directQueue){//将队列和交换机绑定, 并设置用于匹配键:routingKey路由键return BindingBuilder.bind(directQueue).to(directExchange).with(DIRECT_ROUTING_KEY);}
(4)创建死信交换器、死信队列、绑定关系
@Beanpublic CustomExchange delayExchange(){Map<String, Object> args = new HashMap<>();args.put("x-delayed-type", "direct");return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, args);}@Beanpublic Queue delayQueue(){Queue queue = new Queue(DELAY_QUEUE, true);return queue;}@Beanpublic Binding delaybinding(Queue delayQueue, CustomExchange delayExchange){return BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAY_ROUTING_KEY).noargs();}
(5)发送消息方(立即发送JSON格式数据/延迟发送Map格式数据)
①实体类
package com.pjb.entity;/*** 用户信息实体类**/
public class UserInfo
{private int userId; //用户编号private String userName; //用户姓名private String blogUrl; //博客地址private String blogRemark; //博客信息//省略getter与setter方法...
}
②service层
package com.pjb.sender;import com.pjb.entity.UserInfo;import java.util.Map;/*** 用户消息发送服务接口**/
public interface UserSender
{/*** 发送用户信息Json格式数据* @param userInfo 用户信息实体类*/public void sendUserJson(UserInfo userInfo);/*** 延时发送用户信息Map格式数据* @param userMap 用户信息Map*/public void sendDelayUserMap(Map userMap);
}
③serviceImpl类
package com.pjb.sender.impl;import com.pjb.config.RabbitMqConfig;
import com.pjb.entity.UserInfo;
import com.pjb.sender.UserSender;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;/*** 用户消息发送服务类**/
@Service
public class UserSenderImpl implements UserSender
{@AutowiredRabbitTemplate rabbitTemplate;//时间格式SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/*** 发送用户信息Json格式数据* @param userInfo 用户信息实体类*/@Overridepublic void sendUserJson(UserInfo userInfo){rabbitTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE, RabbitMqConfig.DIRECT_ROUTING_KEY, userInfo);System.out.println("Json格式数据消息发送成功,发送时间:" + dateFormat.format(new Date()));}/*** 延时发送用户信息Map格式数据* @param userMap 用户信息Map*/@Overridepublic void sendDelayUserMap(Map userMap){rabbitTemplate.convertAndSend(RabbitMqConfig.DELAY_EXCHANGE, RabbitMqConfig.DELAY_ROUTING_KEY, userMap, new MessagePostProcessor(){@Overridepublic Message postProcessMessage(Message message) throws AmqpException{//消息延迟5秒message.getMessageProperties().setHeader("x-delay", 5000);return message;}});System.out.println("Map格式数据消息发送成功,发送时间:" + dateFormat.format(new Date()));}
}
- 发送消息核心方法:
/*** 发送消息,参数说明:* String exchange:交换器名称。* String routingKey:路由键。* Object object:发送内容。*/rabbitTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE, RabbitMqConfig.DIRECT_ROUTING_KEY, userInfo);
7.2消息接收端
7.2.1引入依赖
<!-- AMQP客户端 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
7.2.2yml配置
spring:# 项目名称application:name: rabbitmq-consumer# RabbitMQ服务配置rabbitmq:host: 127.0.0.1port: 5672username: guestpassword: guestlistener:simple:# 重试机制retry:enabled: true #是否开启消费者重试max-attempts: 5 #最大重试次数initial-interval: 5000ms #重试间隔时间(单位毫秒)max-interval: 1200000ms #重试最大时间间隔(单位毫秒)multiplier: 2 #间隔时间乘子,间隔时间*乘子=下一次的间隔时间,最大不能超过设置的最大间隔时间
7.2.3RabbitMQConfig配置类——(非常重要)
package com.pjb.config;import com.pjb.receiver.impl.AckReceiver;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** RabbitMQ配置类* @author pan_junbiao**/
@Configuration
public class RabbitMqConfig
{public static final String DIRECT_QUEUE = "direct_queue"; //Direct队列名称public static final String DELAY_QUEUE = "delay_queue"; //延时队列名称/*** 消息接收确认处理类*/@Autowiredprivate AckReceiver ackReceiver;@Autowiredprivate CachingConnectionFactory connectionFactory;/*** 客户端配置* 配置手动确认消息、消息接收确认*/@Beanpublic SimpleMessageListenerContainer simpleMessageListenerContainer(){//消费者数量,默认10int DEFAULT_CONCURRENT = 10;//每个消费者获取最大投递数量 默认50int DEFAULT_PREFETCH_COUNT = 50;SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);container.setConcurrentConsumers(DEFAULT_CONCURRENT);container.setMaxConcurrentConsumers(DEFAULT_PREFETCH_COUNT);// RabbitMQ默认是自动确认,这里改为手动确认消息container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//添加队列,可添加多个队列container.addQueues(new Queue(DIRECT_QUEUE,true));container.addQueues(new Queue(DELAY_QUEUE,true));//设置消息处理类container.setMessageListener(ackReceiver);return container;}
}
7.2.4统一消息处理类——AckReceiver
package com.pjb.receiver.impl;import com.pjb.config.RabbitMqConfig;
import com.pjb.receiver.UserReceiver;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;
import java.util.Date;/*** 消息接收确认处理类* 所有的消息,都由该类接收* @author pan_junbiao**/
@Service
public class AckReceiver implements ChannelAwareMessageListener
{/*** 用户消息接收类*/@Autowiredprivate UserReceiver userReceiver;@Overridepublic void onMessage(Message message, Channel channel) throws Exception{//时间格式SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println("消息接收成功,接收时间:" + dateFormat.format(new Date()) + "\n");//获取队列名称String queueName = message.getMessageProperties().getConsumerQueue();//接收用户信息Json格式数据if (queueName.equals(RabbitMqConfig.DIRECT_QUEUE)){userReceiver.receiverUserJson(message, channel);}//延时接收用户信息Map格式数据if (queueName.equals(RabbitMqConfig.DELAY_QUEUE)){userReceiver.receiverDelayUserMap(message, channel);}//多个队列的处理,则如上述代码,继续添加方法....}
}
7.2.5接收消息
package com.pjb.receiver;import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;/*** 用户消息接收接口**/
public interface UserReceiver
{/*** 接收用户信息Json格式数据*/public void receiverUserJson(Message message, Channel channel) throws Exception;/*** 延时接收用户信息Map格式数据*/public void receiverDelayUserMap(Message message, Channel channel) throws Exception;
}
(1)接收JSON数据
/*** 接收用户信息Json格式数据*/@Overridepublic void receiverUserJson(Message message, Channel channel) throws Exception{ //获取消息唯一idlong deliveryTag = message.getMessageProperties().getDeliveryTag();try{//将JSON格式数据转换为实体对象——非常重要、重要、重要ObjectMapper mapper = new ObjectMapper();UserInfo userInfo = mapper.readValue(message.getBody(), UserInfo.class);System.out.println("接收者收到JSON格式消息:");System.out.println("用户编号:" + userInfo.getUserId());System.out.println("用户名称:" + userInfo.getUserName());System.out.println("博客地址:" + userInfo.getBlogUrl());System.out.println("博客信息:" + userInfo.getBlogRemark());//确认消息channel.basicAck(deliveryTag, true);/*** 否定消息,参数说明:* long deliveryTag:唯一标识 ID。* boolean multiple:是否批处理,当该参数为 true 时,* 则可以一次性确认 deliveryTag 小于等于传入值的所有消息。* boolean requeue:如果 requeue 参数设置为 true,* 则 RabbitMQ 会重新将这条消息存入队列,以便发送给下一个订阅的消费者;* 如果 requeue 参数设置为 false,则 RabbitMQ 立即会还把消息从队列中移除,* 而不会把它发送给新的消费者。*///channel.basicNack(deliveryTag, true, false);}catch (Exception e){/*** 拒绝消息,参数说明:* long deliveryTag:唯一标识 ID。* boolean requeue:如果 requeue 参数设置为 true,* 则 RabbitMQ 会重新将这条消息存入队列,以便发送给下一个订阅的消费者;* 如果 requeue 参数设置为 false,则 RabbitMQ 立即会还把消息从队列中移除,* 而不会把它发送给新的消费者。*/channel.basicReject(deliveryTag, false);e.printStackTrace();}}
(2)接收map数据
/*** 延时接收用户信息Map格式数据*/@Overridepublic void receiverDelayUserMap(Message message, Channel channel) throws Exception{long deliveryTag = message.getMessageProperties().getDeliveryTag();try{//将JSON格式数据转换为Map对象ObjectMapper mapper = new ObjectMapper();JavaType javaType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);Map<String, Object> resultMap = mapper.readValue(message.getBody(),javaType);System.out.println("接收者收到Map格式消息:");System.out.println("用户编号:" + resultMap.get("userId"));System.out.println("用户名称:" + resultMap.get("userName"));System.out.println("博客地址:" + resultMap.get("blogUrl"));System.out.println("博客信息:" + resultMap.get("userRemark"));//确认消息channel.basicAck(deliveryTag, true);//否定消息//channel.basicNack(deliveryTag, true, false);}catch (Exception e){//拒绝消息channel.basicReject(deliveryTag, false);e.printStackTrace();}}
7.3总结
- RabbitMQ系列第七篇文章主要介绍了如何实现JSON、Map格式数据的发送与接收;
- 在发送服务端中,核心为RabbitMQ的配置文件(配置json转换器、设置交换机、队列、绑定交换机与队列)发送消息的核心方法为RabbitTemplate.convertAndSend方法,传入指定交换机、路由键、以及要发送的消息内容;
- 在接收服务端中,核心依然为配置文件中的客户端配置:①手动确认信息;②添加监听队列;③设置统一消息处理类,接着在消息处理类中获取消息的队列名称,根据不同的队列名称调用不同的消息处理类;
- 在接收json格式的处理类中,通过ObjectMapper对象的readValue方法,将message中的body内容,转成想要的对象;
- 在接收map格式的处理中,先通过ObjectMapper对象的getTypeFactroy()的constructMapType(),构造出JavaType对象,接着使用ObjectMapper对象的readValue方法和JavaType对象,将message中的body内容转成map格式