上节的适配器不变,在适配器中添加一个转换器TextMessageConverter,
完成将byte数组转换成String字符串
//1.适配器方式:默认是有自己的方法的名字的:handleMessage MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate()); //自己指定一个默认的方法名 adapter.setDefaultListenerMethod("consumeMessage"); //也可以加一个转换器:从字节数组转换为String adapter.setMessageConverter(new TextMessageConverter()); container.setMessageListener(adapter);
TextMessageConverter代码:
package com.dwz.spring.converter; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.support.converter.MessageConversionException; import org.springframework.amqp.support.converter.MessageConverter; public class TextMessageConverter implements MessageConverter { //将其它对象转换成Message @Override public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException { return new Message(object.toString().getBytes(), messageProperties); } //将Message对象转换成String @Override public Object fromMessage(Message message) throws MessageConversionException { String contentType = message.getMessageProperties().getContentType(); if(null != contentType && contentType.contains("text")) { System.err.println("contentType:--String--" + contentType); return new String(message.getBody()); } return message.getBody(); } }
此时我们适配器自定义的委托对象MessageDelegate的consumeMessage()接收的参数类型要与 fromMessage()返回的类型一致
MessageDelegate类如下:
public class MessageDelegate { public void consumeMessage(String messageBody) { System.err.println("consumeMessage默认方法,消息内容:String--" + messageBody); } }