首页 > 解决方案 > 使用 JmsTemplate 异步发送消息观察到的延迟

问题描述

JmsTemplate 没有内置 API 来支持 JMS 2.0 异步发送。我使用 ProducerCallback 对象并直接在 JMS MessageProducer 上调用 JMS 2.0 异步发送 API。

消息发送成功。但是如果我发送 2 条大消息(2M 消息),第二次发送将比发送第一条消息花费更多时间。

根据我的测试,第一次发送需要 133ms,第二次发送需要 10417ms。看起来它发送第二条消息,直到完成发送第一条消息。

但是,如果我直接使用原始 JMS 2.0 异步发送 API(不使用 JmsTemplate),则不会阻止第二次发送。根据我的测试,第一次发送需要 50 毫秒,第二次发送需要 63 毫秒。

以下代码是我使用的 JmsTemplate,Spring JMS 中是否有任何特殊处理会阻止第二条消息发送?

public void sendQueueMsgAsync(String msg, CompletionListener completionListener) {
  jmsQueueTemplate.execute(new ProducerCallback() {

   @Override
   public Object doInJms(Session session, MessageProducer producer) throws JMSException {
    TextMessage txtMsg = session.createTextMessage();
    txtMsg.setText(msg);
    producer.send(txtMsg, completionListener);
    return null;
   }
  });
 }

比我调用它两次发送 2 条消息。

start = System.currentTimeMillis();
springJmsService.sendQueueMsgAsync(msgToSend, listener1);
end = System.currentTimeMillis();
timeTaken = end - start;
logger.info("send async queue msg taken1=" + timeTaken);

start = System.currentTimeMillis();
springJmsService.sendQueueMsgAsync(msgToSend, listener2);
end = System.currentTimeMillis();
timeTaken = end - start;
logger.info("send async queue msg taken2=" + timeTaken);

标签: spring-jmsjmstemplate

解决方案


推荐阅读