我试图设置一个简单的Spring AMQP场景,但是收到以下错误:
Could not resolve method parameter at index 0 in method:
public void handleMessage(HelloMessage),
with 1 error(s): [Error in object 'msg': codes []; arguments [];
default message [@Payload param is required]]
我不理解错误消息,根据文档here,我的印象是我可以使用任何POJO发送和接收消息。
这是一个非常简单的设置:
主
public class Program {
private static ConfigurableApplicationContext applicationContext;
public static void main(String[] args) {
try {
startApp();
System.out.println("Running...");
System.in.read();
applicationContext.close();
System.out.println("Shutting down...");
}
catch (Throwable e) {
e.printStackTrace();
}
}
private static void startApp() {
applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
applicationContext.refresh();
MessageSender messageSender = applicationContext.getBean(MessageSender.class);
messageSender.sendMessage("hello", 1);
}
应用context.xml中
<context:component-scan base-package="org.abiri.amqpTest" />
<rabbit:connection-factory id="connectionFactory"
host="localhost" port="5672"
username="guest" password="guest"/>
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>
<rabbit:admin connection-factory="connectionFactory"/>
<rabbit:queue name="hello"/>
<bean id="rabbitListenerContainerFactory"
class="org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="concurrentConsumers" value="3"/>
<property name="maxConcurrentConsumers" value="10"/>
</bean>
<rabbit:annotation-driven container-factory="rabbitListenerContainerFactory"/>
<rabbit:listener-container connection-factory="connectionFactory" />
messageSender,和
@Service
public class MessageSender {
@Autowired
private AmqpTemplate amqpTemplate;
// Accessors...
public void sendMessage(String message, Integer sillyNumber) {
amqpTemplate.convertAndSend("hello",
new HelloMessage(message, sillyNumber));
}
}
消息监听
@Component
public class MessageListener {
@RabbitListener(queues = "hello")
public void handleMessage(HelloMessage msg) {
out.println(format("Received message: %s with silly number: %d",
msg.getMessage(), msg.getSillyNumber()));
}
}
HelloMessage
public class HelloMessage {
private String message;
private Integer sillyNumber;
// Empty constructor, full constructor and accessors
}
我能够验证消息确实已发送并且在队列中:
RabbitMQ通过自制程序默认安装。
答案 0 :(得分:8)
你的问题非常简单!
要使用默认SimpleMessageConverter
通过RabbitMQ发送任何Java对象,您必须将您的类标记为Serializable
:
public class HelloMessage implements Serializable {
....
}
当然,listener
应用程序应该在其CLASSPATH中具有相同的类,以便能够deserialize
byte[]
从payload
(AMQP消息正文)到相应的HelloMessage
对象。