Spring AMQP是对AMQP协议的抽象和封装,从官方网站上得知它是由两个项目组成的(spring-amqp和spring-rabbit)。在使用Spring整合RabbitMQ时我们主要关注三个核心接口(MessageListenerContainer、RabbitAdmin以及RabbitTemplate)
RabbitAdmin: 用于声明交换机 队列 绑定等
RabbitTemplate: 用于RabbitMQ消息的发送和接收
MessageListenerContainer: 监听容器 为消息入队提供异步处理
使用Spring整合RabbitMQ需要导入如下依赖
<dependency>
<groupId>org.springframework.amqpgroupId>
<artifactId>spring-rabbitartifactId>
<version>2.0.2.RELEASEversion>
dependency>
本系列博客源码GIT地址:https://github.com/RobertoHuang/RGP-RABBITMQ.git
1.创建生产者配置类 将RabbitAdmin、RabbitTemplate纳入Spring管理
@Configuration
public class SpringAMQPProducerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
// 配置连接信息
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
// 网络异常自动连接恢复
connectionFactory.setAutomaticRecoveryEnabled(true);
// 每10秒尝试重试连接一次
connectionFactory.setNetworkRecoveryInterval(10000);
// 设置ConnectionFactory属性信息
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
}
}
2.创建生产者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.manual.declare.producer")
public class ProducerApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProducerApplication.class);
RabbitAdmin rabbitAdmin = context.getBean(RabbitAdmin.class);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
// 声明交换机
rabbitAdmin.declareExchange(new DirectExchange("roberto.order", true, false, new HashMap<>()));
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("UTF-8");
Message message = new Message("订单信息".getBytes(), messageProperties);
// 发布消息 (交换机名, Routing key, 消息);
// 发布消息还可以使用rabbitTemplate.convertAndSend(); 其支持消息后置处理
rabbitTemplate.send("roberto.order", "add", message);
}
}
3.创建消费者配置类 将RabbitAdmin纳入Spring管理,并在MessageListenerContainer类中定义了消息消费的逻辑
@Configuration
public class SpringAMQPConsumerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
// 配置连接信息
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
// 网络异常自动连接恢复
connectionFactory.setAutomaticRecoveryEnabled(true);
// 每10秒尝试重试连接一次
connectionFactory.setNetworkRecoveryInterval(10000);
// 设置ConnectionFactory属性信息
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer();
messageListenerContainer.setConnectionFactory(connectionFactory);
messageListenerContainer.setQueueNames("roberto.order.add");
// 设置消费者线程数
messageListenerContainer.setConcurrentConsumers(5);
// 设置最大消费者线程数
messageListenerContainer.setMaxConcurrentConsumers(10);
// 设置消费者属性信息
Map argumentMap = new HashMap();
messageListenerContainer.setConsumerArguments(argumentMap);
// 设置消费者标签
messageListenerContainer.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String s) {
return "RGP订单系统ADD处理逻辑消费者";
}
});
// 使用setAutoStartup方法可以手动设置消息消费时机
messageListenerContainer.setAutoStartup(false);
// 使用setAfterReceivePostProcessors方法可以增加消息后置处理器
// messageListenerContainer.setAfterReceivePostProcessors();
messageListenerContainer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
System.out.println(new String(message.getBody(), "UTF-8"));
System.out.println(message.getMessageProperties());
} catch (Exception e) {
e.printStackTrace();
}
}
});
return messageListenerContainer;
}
}
4.创建消费者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.manual.declare.consumer")
public class ConsumerApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerApplication.class);
RabbitAdmin rabbitAdmin = context.getBean(RabbitAdmin.class);
MessageListenerContainer messageListenerContainer = context.getBean(MessageListenerContainer.class);
// 声明队列 (队列名", 是否持久化, 是否排他, 是否自动删除, 队列属性);
rabbitAdmin.declareQueue(new Queue("roberto.order.add", true, false, false, new HashMap<>()));
// 声明Direct Exchange (交换机名, 是否持久化, 是否自动删除, 交换机属性);
rabbitAdmin.declareExchange(new DirectExchange("roberto.order", true, false, new HashMap<>()));
// 将队列Binding到交换机上 Routing key为add
rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("roberto.order.add")).to(new DirectExchange("roberto.order")).with("add"));
// 开始监听队列
messageListenerContainer.start();
}
}
5.依次启动消息消费者和生产者 控制台输出如下
订单信息
MessageProperties [headers={}, contentType=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=roberto.order, receivedRoutingKey=add, deliveryTag=1, consumerTag=RGP订单系统ADD处理逻辑消费者, consumerQueue=roberto.order.add]
上诉代码使用Spring整合RabbitMQ,最终实现效果和上一篇博客介绍RabbitMQ Java Client一致
在上诉的Demo中我们是手动使用RabbitAdmin对交换机、队列和绑定进行声明的,Spring AMQP还提供了自动声明方式交换机、队列和绑定。我们可以直接把要自动声明的组件纳入Spring容器中管理即可,自动声明发生在RabbitMQ第一次连接创建的时候,自动声明支持单个和批量自动声明。使用自动声明需要符合如下条件:
1.需要有连接产生
2.RabbitAdmin必须交由Spring管理,且autoStartup必须为true(默认)
3.如果ConnectionFactory使用的是CachingConnectionFactory,则cacheMode必须要为CacheMode.CHANNEL
4.所有要声明的组件的shouldDeclare必须为true
5.要声明的Queue名称不能以amq.开头
上诉规则定义在RabbitAdmin的afterPropertiesSet方法中,有兴趣的同学可以自行阅读RabbitAdmin源码
1.创建生产者配置类 将RabbitAdmin、RabbitTemplate纳入Spring管理
@Configuration
public class SpringAMQPProducerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
// 配置连接信息
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
// 网络异常自动连接恢复
connectionFactory.setAutomaticRecoveryEnabled(true);
// 每10秒尝试重试连接一次
connectionFactory.setNetworkRecoveryInterval(10000);
// 设置ConnectionFactory属性信息
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
}
}
2.创建生产者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.auto.declare.producer")
public class ProducerApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(roberto.growth.process.rabbitmq.spring.amqp.manual.declare.producer.ProducerApplication.class);
RabbitAdmin rabbitAdmin = context.getBean(RabbitAdmin.class);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
// 声明交换机
rabbitAdmin.declareExchange(new DirectExchange("roberto.order", true, false, new HashMap<>()));
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("UTF-8");
Message message = new Message("订单信息".getBytes(), messageProperties);
// 发布消息 (交换机名, Routing key, 消息);
// 发布消息还可以使用rabbitTemplate.convertAndSend(); 其支持消息后置处理
rabbitTemplate.send("roberto.order", "add", message);
}
}
3.创建消费者配置类 将RabbitAdmin纳入Spring管理,并在MessageListenerContainer类中定义了消息消费的逻辑,并且在该配置类中声明交换机,队列,绑定
@Configuration
public class SpringAMQPConsumerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
// 配置连接信息
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
// 网络异常自动连接恢复
connectionFactory.setAutomaticRecoveryEnabled(true);
// 每10秒尝试重试连接一次
connectionFactory.setNetworkRecoveryInterval(10000);
// 设置ConnectionFactory属性信息
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
// 自动声明交换机
// 如果要一次性声明多个 使用public List listExchange()即可
public Exchange exchange() {
return new DirectExchange("roberto.order", true, false, new HashMap<>());
}
@Bean
// 自动声明队列
// 如果要一次性声明多个 使用public List listQueue()即可
public Queue queue() {
return new Queue("roberto.order.add", true, false, false, new HashMap<>());
}
@Bean
// 自动声明绑定
// 如果要一次性声明多个 使用public List listBinding()即可
public Binding binding() {
return new Binding("roberto.order.add", Binding.DestinationType.QUEUE, "roberto.order", "add", new HashMap<>());
}
@Bean
public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer();
messageListenerContainer.setConnectionFactory(connectionFactory);
messageListenerContainer.setQueueNames("roberto.order.add");
// 设置消费者线程数
messageListenerContainer.setConcurrentConsumers(5);
// 设置最大消费者线程数
messageListenerContainer.setMaxConcurrentConsumers(10);
// 设置消费者属性信息
Map argumentMap = new HashMap();
messageListenerContainer.setConsumerArguments(argumentMap);
// 设置消费者标签
messageListenerContainer.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String s) {
return "RGP订单系统ADD处理逻辑消费者";
}
});
// 使用setAutoStartup方法可以手动设置消息消费时机
messageListenerContainer.setAutoStartup(true);
// 使用setAfterReceivePostProcessors方法可以增加消息后置处理器
// messageListenerContainer.setAfterReceivePostProcessors();
messageListenerContainer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
System.out.println(new String(message.getBody(), "UTF-8"));
System.out.println(message.getMessageProperties());
} catch (Exception e) {
e.printStackTrace();
}
}
});
return messageListenerContainer;
}
}
4.创建消费者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.auto.declare.consumer")
public class ConsumerApplication {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ConsumerApplication.class);
}
}
5.依次启动消息消费者和生产者 控制台输出如下
订单信息
MessageProperties [headers={}, contentType=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=roberto.order, receivedRoutingKey=add, deliveryTag=1, consumerTag=RGP订单系统ADD处理逻辑消费者, consumerQueue=roberto.order.add]
该代码与上诉代码实现的效果一致,只是将交换机,队列,绑定进行了自动声明
以上两个Demo在消费消息处理逻辑时往MessageListenerContainer中传递了MessageListener,但是我们有时候已经写好了消费逻辑对应的类,我们不希望它去扩展MessageListener/ChannelAwareMessageListener,因为这么做的话意味着我们需要改变现有代码。Spring AMQP提供了消息处理器适配器的功能,它可以把一个纯POJO类适配成一个可以处理消息的处理器,默认处理消息的方法为handleMessage,可以通过setDefaultListenerMethod方法进行修改
1.创建生产者配置类
@Configuration
public class SpringAMQPProducerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setNetworkRecoveryInterval(10000);
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
}
}
2.创建生产者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.message.listener.adapte.producer")
public class ProducerApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProducerApplication.class);
RabbitAdmin rabbitAdmin = context.getBean(RabbitAdmin.class);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
rabbitAdmin.declareExchange(new DirectExchange("roberto.order", true, false, new HashMap<>()));
MessageProperties messageProperties = new MessageProperties();
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("UTF-8");
Message message = new Message("订单信息".getBytes(), messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
}
3.创建消费者消息处理器类,它可是是纯POJO类
public class MessageHandle {
public void add(byte[] message){
try {
System.out.println(new String(message,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
4.创建消费者配置类 配置自定义消息处理器(将roberto.order.add队列使用自定义消息处理类的add方法进行处理)
@Configuration
public class SpringAMQPConsumerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setNetworkRecoveryInterval(10000);
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public Exchange exchange() {
return new DirectExchange("roberto.order", true, false, new HashMap<>());
}
@Bean
public Queue queue() {
return new Queue("roberto.order.add", true, false, false, new HashMap<>());
}
@Bean
public Binding binding() {
return new Binding("roberto.order.add", Binding.DestinationType.QUEUE, "roberto.order", "add", new HashMap<>());
}
@Bean
public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer();
messageListenerContainer.setConnectionFactory(connectionFactory);
messageListenerContainer.setQueueNames("roberto.order.add");
messageListenerContainer.setConcurrentConsumers(5);
messageListenerContainer.setMaxConcurrentConsumers(10);
Map argumentMap = new HashMap();
messageListenerContainer.setConsumerArguments(argumentMap);
messageListenerContainer.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String s) {
return "RGP订单系统ADD处理逻辑消费者";
}
});
messageListenerContainer.setAutoStartup(true);
// 新建消息处理器适配器
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(new MessageHandle());
// 设置默认处理消息方法
messageListenerAdapter.setDefaultListenerMethod("handleMessage");
Map queueOrTagToMethodName = new HashMap<>();
// 将roberto.order.add队列的消息 使用add方法进行处理
queueOrTagToMethodName.put("roberto.order.add","add");
messageListenerAdapter.setQueueOrTagToMethodName(queueOrTagToMethodName);
messageListenerContainer.setMessageListener(messageListenerAdapter);
return messageListenerContainer;
}
}
5.创建消费者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.message.listener.adapte.consumer")
public class ConsumerApplication {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ConsumerApplication.class);
}
}
6.依次启动消息消费者和生产者 控制台输出如下
订单信息
如上Demo说明我们可以将一个纯POJO类定义为消息处理器,并且不用去扩展MessageListener/ChannelAwareMessageListener接口,关于自定义处理器方法的参数默认情况下为byte[]类型,这是由Spring AMQP默认消息转换器(SimpleMessageConverter)决定的,接下来我们将介绍Spring AMQP的消息转换器功能
在上诉例子中我们定义的add(byte[] message)方法的参数是一个字节数组,但是有时候我们往RabbitMQ中发送的是一个JSON对象,我们希望在处理消息的时候它已经自动帮我们转为JAVA对象;又或者我们往RabbitMQ中发送的是一张图片或其他格式的文件,我们希望在处理消息的时候它已经自动帮我们转成文件格式,我们可以手动设置MessageConverter来实现如上需求,如果未设置MessageConverter则使用Spring AMQP默认提供的SimpleMessageConverter
以下例子使用MessageConverter实现了当生产者往RabbitMQ发送不同类型的数据的时候,使用MessageHandle不同的方法进行处理,需要注意的是当生产者在发送JSON数据的时候,需要制定这个JSON是哪个对象,用于Spring AMQP转换,规则如下
当发送普通对象的JSON数据时,需要在消息的header中增加一个__TypeId__的属性告知消费者是哪个对象
当发送List集合对象的JSON数据时,需要在消息的header中将__TypeId__指定为java.util.List,并且需要额外指定属性__ContentTypeId__用户告知消费者List集合中的对象类型
当发送Map集合对象的JSON数据时,需要在消息的header中将__TypeId__指定为java.util.Map,并且需要额外指定属性__KeyTypeId__用于告知客户端Map中key的类型,__ContentTypeId__用于告知客户端Map中Value的类型
1.创建订单实体类
public class Order {
/**
* 订单编号
**/
private String orderId;
/**
* 订单金额
**/
private BigDecimal orderAmount;
public Order() {
}
public Order(String orderId, BigDecimal orderAmount) {
this.orderId = orderId;
this.orderAmount = orderAmount;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
}
2.自定义文件消息转换器
public class FileMessageConverter implements MessageConverter {
@Override
public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
return null;
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
String extName = (String) message.getMessageProperties().getHeaders().get("_extName");
byte[] bytes = message.getBody();
String fileName = UUID.randomUUID().toString();
String filePath = System.getProperty("java.io.tmpdir") + fileName + "." + extName;
File tempFile = new File(filePath);
try {
FileCopyUtils.copy(bytes, tempFile);
} catch (IOException e) {
throw new MessageConversionException("FileMessageConverter消息转换失败", e);
}
return tempFile;
}
}
3.自定义字符串消息转换器
public class StringMessageConverter implements MessageConverter{
@Override
public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
return null;
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
try {
return new String(message.getBody(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new MessageConversionException("StringMessageConverter转换失败", e);
}
}
}
4.自定义消息处理器类
public class MessageHandle {
public void add(byte[] body) {
System.out.println("----------byte[]方法进行处理----------");
System.out.println("body");
}
public void add(String message) {
System.out.println("----------String方法进行处理----------");
System.out.println(message);
}
public void add(File file) {
System.out.println("----------File方法进行处理----------");
System.out.println(file.length());
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
}
public void add(Order order) {
System.out.println("----------Order方法进行处理----------");
System.out.println(order.getOrderId() + "---" + order.getOrderAmount());
}
public void add(List orderList) {
System.out.println("----------List方法进行处理----------" );
System.out.println(orderList.size());
for (Order order : orderList) {
System.out.println(order.getOrderId() + "---" + order.getOrderAmount());
}
}
public void add(Map orderMap) {
System.out.println("----------Map方法进行处理----------" );
for (Map.Entry entry : orderMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().getOrderId() + "---" + entry.getValue().getOrderAmount());
}
}
}
5.创建生产者配置类
@Configuration
public class SpringAMQPProducerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setNetworkRecoveryInterval(10000);
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
}
}
6.创建生产者启动类 发送多条不同消息类型消息
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.message.converter.producer")
public class ProducerApplication {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProducerApplication.class);
RabbitAdmin rabbitAdmin = context.getBean(RabbitAdmin.class);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
rabbitAdmin.declareExchange(new DirectExchange("roberto.order", true, false, new HashMap<>()));
// 发送字符串
sendString(rabbitTemplate);
// 发送当个对象JSON
sendSingle(rabbitTemplate);
// 发送List集合JSON
sendList(rabbitTemplate);
// 发送Map集合JSON
sendMap(rabbitTemplate);
// 发送图片
sendImage(rabbitTemplate);
}
public static void sendString(RabbitTemplate rabbitTemplate) {
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("text/plain");
Message message = new Message("订单消息".getBytes(), messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
public static void sendSingle(RabbitTemplate rabbitTemplate) throws Exception {
Order order = new Order("OD0000001", new BigDecimal(888888.888888));
ObjectMapper objectMapper = new ObjectMapper();
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.getHeaders().put("__TypeId__", "order");
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("application/json");
Message message = new Message(objectMapper.writeValueAsString(order).getBytes(), messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
public static void sendList(RabbitTemplate rabbitTemplate) throws Exception {
Order order = new Order("OD0000001", new BigDecimal(888888.888888));
Order order2 = new Order("OD0000002", new BigDecimal(888888.888888));
List orderList = Arrays.asList(order, order2);
ObjectMapper objectMapper = new ObjectMapper();
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.getHeaders().put("__TypeId__", "java.util.List");
messageProperties.getHeaders().put("__ContentTypeId__", "order");
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("application/json");
Message message = new Message(objectMapper.writeValueAsString(orderList).getBytes(), messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
public static void sendMap(RabbitTemplate rabbitTemplate) throws Exception {
Order order = new Order("OD0000001", new BigDecimal(888888.888888));
Order order2 = new Order("OD0000002", new BigDecimal(888888.888888));
Map orderMap = new HashMap<>();
orderMap.put(order.getOrderId(), order);
orderMap.put(order2.getOrderId(), order2);
ObjectMapper objectMapper = new ObjectMapper();
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.getHeaders().put("__TypeId__", "java.util.Map");
messageProperties.getHeaders().put("__KeyTypeId__", "java.lang.String");
messageProperties.getHeaders().put("__ContentTypeId__", "order");
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("application/json");
Message message = new Message(objectMapper.writeValueAsString(orderMap).getBytes(), messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
public static void sendImage(RabbitTemplate rabbitTemplate) throws Exception {
File file = new File("E:\\a.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
int length;
byte[] b = new byte[1024];
while ((length = fileInputStream.read(b)) != -1) {
byteArrayOutputStream.write(b, 0, length);
}
fileInputStream.close();
byteArrayOutputStream.close();
byte[] buffer = byteArrayOutputStream.toByteArray();
// 声明消息 (消息体, 消息属性)
MessageProperties messageProperties = new MessageProperties();
messageProperties.getHeaders().put("_extName", "jpg");
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setContentType("image/jpg");
Message message = new Message(buffer, messageProperties);
rabbitTemplate.send("roberto.order", "add", message);
}
}
7.创建消费者配置类 为不同ContentType消息设置消息转换器
@Configuration
public class SpringAMQPConsumerConfig {
@Bean
public ConnectionFactory connectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.setHost("192.168.56.128");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("roberto");
connectionFactory.setPassword("roberto");
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setNetworkRecoveryInterval(10000);
Map connectionFactoryPropertiesMap = new HashMap();
connectionFactoryPropertiesMap.put("principal", "RobertoHuang");
connectionFactoryPropertiesMap.put("description", "RGP订单系统V2.0");
connectionFactoryPropertiesMap.put("emailAddress", "[email protected]");
connectionFactory.setClientProperties(connectionFactoryPropertiesMap);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
public Exchange exchange() {
return new DirectExchange("roberto.order", true, false, new HashMap<>());
}
@Bean
public Queue queue() {
return new Queue("roberto.order.add", true, false, false, new HashMap<>());
}
@Bean
public Binding binding() {
return new Binding("roberto.order.add", Binding.DestinationType.QUEUE, "roberto.order", "add", new HashMap<>());
}
@Bean
public MessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer();
messageListenerContainer.setConnectionFactory(connectionFactory);
messageListenerContainer.setQueueNames("roberto.order.add");
messageListenerContainer.setConcurrentConsumers(5);
messageListenerContainer.setMaxConcurrentConsumers(10);
Map argumentMap = new HashMap();
messageListenerContainer.setConsumerArguments(argumentMap);
messageListenerContainer.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String s) {
return "RGP订单系统ADD处理逻辑消费者";
}
});
messageListenerContainer.setAutoStartup(true);
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(new MessageHandle());
messageListenerAdapter.setDefaultListenerMethod("handleMessage");
Map queueOrTagToMethodName = new HashMap<>();
queueOrTagToMethodName.put("roberto.order.add","add");
messageListenerAdapter.setQueueOrTagToMethodName(queueOrTagToMethodName);
messageListenerContainer.setMessageListener(messageListenerAdapter);
// 设置消息转换器
ContentTypeDelegatingMessageConverter converter = new ContentTypeDelegatingMessageConverter();
StringMessageConverter stringMessageConverter = new StringMessageConverter();
FileMessageConverter fileMessageConverter = new FileMessageConverter();
Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
Map> idClassMapping = new HashMap<>();
idClassMapping.put("order", Order.class);
DefaultJackson2JavaTypeMapper javaTypeMapper = new DefaultJackson2JavaTypeMapper();
javaTypeMapper.setIdClassMapping(idClassMapping);
jackson2JsonMessageConverter.setJavaTypeMapper(javaTypeMapper);
// 设置text/html text/plain 使用StringMessageConverter
converter.addDelegate("text/html", stringMessageConverter);
converter.addDelegate("text/plain", stringMessageConverter);
// 设置application/json 使用Jackson2JsonMessageConverter
converter.addDelegate("application/json", jackson2JsonMessageConverter);
// 设置image/jpg image/png 使用FileMessageConverter
converter.addDelegate("image/jpg", fileMessageConverter);
converter.addDelegate("image/png", fileMessageConverter);
messageListenerAdapter.setMessageConverter(converter);
return messageListenerContainer;
}
}
8.创建消费者启动类
@ComponentScan(basePackages = "roberto.growth.process.rabbitmq.spring.amqp.message.converter.consumer")
public class ConsumerApplication {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ConsumerApplication.class);
}
}
9.依次启动消息消费者和生产者 控制台输出如下
----------String方法进行处理----------
订单消息
----------File方法进行处理----------
18758
403e735f-88ff-4bbe-b7d3-a07766de7df9.jpg
C:\Users\ADMINI~1\AppData\Local\Temp\403e735f-88ff-4bbe-b7d3-a07766de7df9.jpg
----------Order方法进行处理----------
OD0000001---888888.888888
----------List<Order>方法进行处理----------
2
OD0000001---888888.888888
OD0000002---888888.888888
----------Map<String, Order>方法进行处理----------
OD0000001
OD0000001---888888.888888
OD0000002
OD0000002---888888.888888
在经过消息转化器后,Spring AMQP会根据最后转换结果的类型找到对应的消息处理方法,在本章中我们只介绍了消息转换器的fromMessage()方法,关于toMessage()将在后续博客中提及