ActiveMQ异步发送使用及常见误区

这段时间一边在重新研究RocketMQ,一边开始看Artemis。RocketMQ现在有很多中文资料,但是Artemis的中文资料很少很少,倒是官方文档不错。后续应该会出一篇Artemis和RocketMQ的介绍文章。

今天要记录的是ActiveMQ的异步发送,直到最近我研究了kafka以后才知道异步发送该这么玩……

ActiveMQ异步发送

ActiveMQ官方说异步发送是很多模式下默认的传输方式,但是在发送非事物持久化消息的时候默认使用的是同步发送模式。

The good news is that ActiveMQ sends message in async mode by default in several cases. It is only in cases where the JMS specification required the use of sync sending that we default to sync sending. The cases that we are forced to send in sync mode are when persistent messages are being sent outside of a transaction.

同步发送时,Producer.send() 方法会被阻塞,直到 broker 发送一个确认消息给生产者,这个确认消息暗示生产者 broker 已经成功地将它发送的消息路由到目标目的并把消息保存到二级存储中。

同步发送持久消息能够提供更好的可靠性,但这潜在地影响了程序的相应速度,因为在接受到 broker 的确认消息之前应用程序或线程会被阻塞。如果应用程序能够容忍一些消息的丢失,那么可以使用异步发送。异步发送不会在受到 broker 的确认之前一直阻塞 Producer.send 方法。

有几种方式可以使用异步发送:

  1. 设置ConnectionFactory时指定使用异步
cf = new ActiveMQConnectionFactory("tcp://locahost:61616?jms.useAsyncSend=true");
  1. 不在构造函数中指定,而是修改ConnectionFactory的配置
((ActiveMQConnectionFactory)connectionFactory).setUseAsyncSend(true);
  1. 在实例化后的ActiveMQConnection对象中设置异步发送
((ActiveMQConnection)connection).setUseAsyncSend(true)

发送端代码

对于发送端来说,使用中常常把同步发送和异步发送混淆使用。因为producer.send(message)太深入人心。而在异步发送持久化消息时,这种普通的send方法却会导致消息的丢失。

异步发送丢失消息的场景是:生产者设置UseAsyncSend=true,使用producer.send(msg)持续发送消息。由于消息不阻塞,生产者会认为所有send的消息均被成功发送至MQ。如果服务端突然宕机,此时生产者端内存中尚未被发送至MQ的消息都会丢失。

正确的异步发送方法是需要接收回调的。来看看AMQ提供的UseCase代码吧

    private double benchmarkCallbackRate() throws JMSException, InterruptedException {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(getName());
        int count = 1000;
        final CountDownLatch messagesSent = new CountDownLatch(count);
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            producer.send(session.createTextMessage("Hello"), new AsyncCallback() {
                @Override
                public void onSuccess() {
                    messagesSent.countDown();
                }

                @Override
                public void onException(JMSException exception) {
                    exception.printStackTrace();
                }
            });
        }
        messagesSent.await();
        return 1000.0 * count / (System.currentTimeMillis() - start);
    }

可以看到,producer.send有带上AsyncCallback的方法。该方法中需要重写onSuccess方法和onException方法。onSuccess方法就是表示这条消息成功发送到MQ上,并接收到了MQ持久化后的回调。onException表示MQ返回一个入队异常的回执。在上面的示例中用的是CountDownLatch类在onSuccess中记录。主要是因为onSuccess方法中只能引用final对象。

一般来说,可以写成下面的形式

public void sendMessage(ActiveMQMessage msg, final String msgid) throws JMSException {
     producer.send(msg, new AsyncCallback() {
          @Override
          public void onSuccess() {
              // 使用msgid标识来进行消息发送成功的处理
              System.out.println(msgid+" has been successfully sent.");
          }
          @Override
          public void onException(JMSException exception) {
              // 使用msgid表示进行消息发送失败的处理
              System.out.println(msgid+" fail to send to mq.");
              exception.printStackTrace();
          }
      });
}

同步发送和异步发送的区别就在此,同步发送等send不阻塞了就表示一定发送成功了,可是异步发送需要接收回执并由客户端再判断一次是否发送成功。

你可能感兴趣的:(ActiveMQ异步发送使用及常见误区)