我有一个消费者消费消息做一些转换并创建一个新的Pojo并传递给制作人。 生产者使用JmsTemplate在队列中发送消息。 生产者应将原始消息的头部设置为(JMSType,JMSCorrelationID,JMSExpiration,JMSDeliveryMode)到要发送的新消息。 但是生产者应该更改原始邮件的replyTo Destination。 我还没有找到创建Destination并设置为JMSReplyTo的方法。 有些人知道我该怎么做?
也许JmsTemplate不是正确的类。
public class Producer {
private final JmsTemplate jmsTemplate;
@Value("${jms-destination}")
private String destination;
public Producer(@Autowired JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void send(final MessageHeaders headers, final Pojo pojo) {
Validate.notNull(order);
jmsTemplate.convertAndSend(destination, pojo, (message) -> {
final Destination replyToDestination = ???;
message.setJMSReplyTo(replyToDestination);
message.setJMSType((String) headers.get(JmsHeaders.TYPE));
message.setJMSCorrelationID((String) headers.get(JmsHeaders.CORRELATION_ID));
message.setJMSExpiration((long) headers.get(JmsHeaders.EXPIRATION));
message.setJMSDeliveryMode((int) headers.get(JmsHeaders.DELIVERY_MODE));
return message;
});
}
}
我发现只有这样做,但我不喜欢,我不确定这会引起副作用:
public class Producer {
private final JmsTemplate jmsTemplate;
@Value("${jms-destination}")
private String destination;
@Value("${jms-replyTo}")
private String replyTo;
public Producer(@Autowired JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void send(final MessageHeaders headers, Pojo pojo) {
Validate.notNull(order);
jmsTemplate.convertAndSend(destination, order, (message) -> {
final Destination replyToDestination = buildReplyTo();
message.setJMSReplyTo(replyToDestination);
message.setJMSType((String) headers.get(JmsHeaders.TYPE));
message.setJMSCorrelationID((String) headers.get(JmsHeaders.CORRELATION_ID));
message.setJMSExpiration((long) headers.get(JmsHeaders.EXPIRATION));
message.setJMSDeliveryMode((int) headers.get(JmsHeaders.DELIVERY_MODE));
return message;
});
}
private Destination buildReplyTo() throws JMSException {
final Session session = jmsTemplate.getConnectionFactory().createConnection()
.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Destination queue =
jmsTemplate.getDestinationResolver().resolveDestinationName(session, replyTo, false);
return queue;
}
}
答案 0 :(得分:0)
您的解决方案会创建侧面连接,但不会关闭。 您应该使用现有的会话对象,并通过send API手动发送pojo。使用getRequiredMessageConverter转换您的pojo。
public void send(final MessageHeaders headers, Pojo pojo) {
Validate.notNull(order);
final String responseQueue = "responseQ";
jmsTemplate.send(destination,
session -> {
Message message = getRequiredMessageConverter().toMessage(message, session);
message.setJMSReplyTo(session.createQueue(responseQueue)); //fill queue
//any other setters
return message;
});
}
// based on Spring JmsTemplate library
private MessageConverter getRequiredMessageConverter() throws IllegalStateException {
MessageConverter converter = jmsTemplate.getMessageConverter();
if (converter == null) {
throw new IllegalStateException("No 'messageConverter' specified. Check configuration of JmsTemplate.");
} else {
return converter;
}
}