🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # ContentTypeDelegatingMessageConverter详解 ## 生产端 ~~~java public class Application { public static void sendOrder( RabbitTemplate rabbitTemplate) throws Exception{ Order order = new Order(); order.setId(1); order.setUserId(1000); order.setAmout(88d); order.setTime(LocalDateTime.now().toString()); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(order); System.out.println(json); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties.getHeaders().put("__TypeId__","order"); Message message = new Message(json.getBytes(),messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void sendUser( RabbitTemplate rabbitTemplate) throws Exception{ User user = new User(); user.setUserId(1000); user.setAge(50); user.setUsername("zhihao.miao"); user.setPassword("123343"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(user); System.out.println(json); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties.getHeaders().put("__TypeId__","user"); Message message = new Message(json.getBytes(),messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void sendOrderList(RabbitTemplate rabbitTemplate) throws Exception{ Order order = new Order(); order.setId(1); order.setUserId(1000); order.setAmout(88d); order.setTime(LocalDateTime.now().toString()); Order order2 = new Order(); order2.setId(2); order2.setUserId(2000); order2.setAmout(99d); order2.setTime(LocalDateTime.now().toString()); List<Order> orderList = Arrays.asList(order,order2); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(orderList); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties.getHeaders().put("__TypeId__","java.util.List"); messageProperties.getHeaders().put("__ContentTypeId__","order"); Message message = new Message(json.getBytes(),messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void sendOrderMap(RabbitTemplate rabbitTemplate) throws Exception{ Order order = new Order(); order.setId(1); order.setUserId(1000); order.setAmout(88d); order.setTime(LocalDateTime.now().toString()); Order order2 = new Order(); order2.setId(2); order2.setUserId(2000); order2.setAmout(99d); order2.setTime(LocalDateTime.now().toString()); Map<String,Object> orderMaps = new HashMap<>(); orderMaps.put("10",order); orderMaps.put("20",order2); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(orderMaps); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties.getHeaders().put("__TypeId__","java.util.Map"); messageProperties.getHeaders().put("__KeyTypeId__","java.lang.String"); messageProperties.getHeaders().put("__ContentTypeId__","order"); Message message = new Message(json.getBytes(),messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void sendJepg(RabbitTemplate rabbitTemplate) throws Exception{ byte[] body = Files.readAllBytes(Paths.get("/Users/naeshihiroshi/Desktop/file/file","aisi.jpeg")); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("image/jepg"); Message message = new Message(body,messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void sendJson( RabbitTemplate rabbitTemplate) throws Exception{ MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); Message message = new Message("hello".getBytes(),messageProperties); rabbitTemplate.send("","zhihao.miao.order",message); } public static void main(String[] args) throws Exception{ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(com.zhihao.miao.day03.Application.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); System.out.println(rabbitTemplate); //sendOrder(rabbitTemplate); //sendUser(rabbitTemplate); //sendOrderList(rabbitTemplate); //sendOrderMap(rabbitTemplate); sendJepg(rabbitTemplate); context.close(); } } ~~~ ## 消费端 ~~~java @Configuration public class MQConfig { @Bean public ConnectionFactory connectionFactory(){ CachingConnectionFactory factory = new CachingConnectionFactory(); factory.setUri("amqp://zhihao.miao:123456@192.168.1.131:5672"); return factory; } @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){ RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); return rabbitAdmin; } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){ RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); return rabbitTemplate; } @Bean public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory){ SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames("zhihao.miao.order"); MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageHandler()); //指定Json转换器 Jackson2JsonMessageConverter jackson2JsonMessageConverter =new Jackson2JsonMessageConverter(); Map<String, Class<?>> idClassMapping = new HashMap<>(); idClassMapping.put("order",Order.class); idClassMapping.put("user",User.class); DefaultJackson2JavaTypeMapper jackson2JavaTypeMapper = new DefaultJackson2JavaTypeMapper(); jackson2JavaTypeMapper.setIdClassMapping(idClassMapping); jackson2JsonMessageConverter.setJavaTypeMapper(jackson2JavaTypeMapper); adapter.setMessageConverter(jackson2JsonMessageConverter); TextMessageConverter textMessageConverter = new TextMessageConverter(); ContentTypeDelegatingMessageConverter contentTypeDelegatingMessageConverter = new ContentTypeDelegatingMessageConverter(); contentTypeDelegatingMessageConverter.addDelegate("text",textMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("html/text",textMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("xml/text",textMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("text/plain",textMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("json",jackson2JsonMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("application/json",jackson2JsonMessageConverter); contentTypeDelegatingMessageConverter.addDelegate("image/jpg",new JPGMessageConverter()); contentTypeDelegatingMessageConverter.addDelegate("image/jepg",new JPGMessageConverter()); contentTypeDelegatingMessageConverter.addDelegate("image/png",new JPGMessageConverter()); adapter.setMessageConverter(contentTypeDelegatingMessageConverter); //设置处理器的消费消息的默认方法 adapter.setDefaultListenerMethod("onMessage"); container.setMessageListener(adapter); return container; } } ~~~ ## 指定的TextMessageConverter消息转换器 ~~~java public class TextMessageConverter implements MessageConverter { @Override public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException { System.out.println("=======toMessage========="); return new Message(object.toString().getBytes(),messageProperties); } @Override public Object fromMessage(Message message) throws MessageConversionException { System.out.println("=======fromMessage========="); return new String(message.getBody()); } } ~~~ ## 指定的JPGMessageConverter消息转换器 ~~~java public class JPGMessageConverter implements MessageConverter{ @Override public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException { return null; } @Override public Object fromMessage(Message message) throws MessageConversionException { System.out.println("====JPGMessageConverter===="); byte[] body = message.getBody(); String fileName = UUID.randomUUID().toString(); String path = "/Users/naeshihiroshi/Desktop/file/"+fileName+".jpg"; File file = new File(path); try{ Files.copy(new ByteArrayInputStream(body),file.toPath()); }catch (IOException e){ e.printStackTrace(); } return file; } } ~~~ ## 客户端消息处理器 ~~~ public class MessageHandler { public void onMessage(byte[] message){ System.out.println("---------onMessage----byte-------------"); System.out.println(new String(message)); } public void onMessage(String message){ System.out.println("---------onMessage---String-------------"); System.out.println(message); } public void onMessage(Order order){ System.out.println("---------onMessage---Order-------------"); System.out.println(order); } public void onMessage(User user){ System.out.println("---------onMessage---user-------------"); System.out.println(user); } public void onMessage(List<Order> orders){ System.out.println("---------onMessage---List<Order>-------------"); orders.stream().forEach(order -> System.out.println(order)); } public void onMessage(Map<String,Object> orderMaps){ System.out.println("-------onMessage---Map<String,Object>------------"); orderMaps.keySet().forEach(key -> System.out.println(orderMaps.get(key))); } public void onMessage(File message){ System.out.println("-------onMessage---File message------------"); System.out.println(message.getName()); } } ~~~ ## 服务器端应用类 ~~~java @ComponentScan public class Application { public static void main(String[] args) throws Exception{ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class); System.out.println("===start up ing======"); TimeUnit.SECONDS.sleep(60); context.close(); } } ~~~ ## 结论 * ContentTypeDelegatingMessageConverter是一个代理的MessageConverter。 * ContentTypeDelegatingMessageConverter本身不做消息转换的具体动作,而是将消息转换委托给具体的MessageConverter。我们可以设置COntentType和MessageConverter的映射关系。 * ContentTypeDelegatingMessageConverter还有一个默认的MessageConverter,也就是说当根据ContentType没有找到映射的MessageConverter的时候,就会使用默认的MessageConverter。