我正在尝试使用支持发布者返回的spring-amqp(RabbitMQ)创建一个侦听器。我找不到这种情况的任何例子,但我尝试做以下事情:
@Component
public class ImportModelHandler {
@Autowired
private ModelService modelService;
public byte[] handleMessage(byte[] file) throws Exception {
try {
if (file == null || file.length == 0) {
throw new IllegalArgumentException("File is empty");
}
return ModelService.OBJECT_MAPPER.writeValueAsBytes(
modelService.importModel(file));
} catch (Exception e) {
return ModelService.OBJECT_MAPPER.writeValueAsBytes(Response.createErrorResponse(e));
}
}
}
Xml配置:
<bean id="importModelListener"
class="org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter">
<constructor-arg ref="importModelHandler"/>
</bean>
<rabbit:connection-factory id="connectionFactory" host="192.168.1.50" port="5672" username="guest" password="guest"
publisher-returns="true"/>
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>
<rabbit:admin connection-factory="connectionFactory"/>
<rabbit:queue name="import.model"/>
<rabbit:queue name="download.model"/>
<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:direct-exchange name="import.model.exchange">
<rabbit:bindings>
<rabbit:binding queue="import.model"/>
</rabbit:bindings>
</rabbit:direct-exchange>
<rabbit:listener-container
connection-factory="connectionFactory">
<rabbit:listener ref="importModelListener" queue-names="import.model"/>
</rabbit:listener-container>
然后我尝试创建用于调用此侦听器的代码:
URL resource = ImportModelTest.class.getResource("/models/model.jar");
File file = new File(resource.toURI());
byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
MessageProperties messageProperties = new MessageProperties();
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_BYTES);
Message message = new Message(bytes, messageProperties);
rabbitTemplate.convertAndSend("import.model", message);
rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
@Override
public void returnedMessage(Message message, int i, String s, String s1, String s2) {
System.out.println(new String(message.getBody()));
}
});
但我有:
org.springframework.amqp.AmqpException:无法确定ReplyTo message属性值:请求消息不包含回复 属性,并且没有设置默认响应。
如何创建将使用Publisher Returns机制的侦听器?