如何在生产者的连接断开时收到通知?

时间:2016-01-22 18:22:53

标签: java activemq

我正在使用嵌入式ActiveMQ代理。 我的目标是找到一种方法来检测队列上的外部生产者何时失去了它的连接。

我这样开始经纪人:

BrokerService broker = new BrokerService();
broker.addConnector("tcp://" + LISTEN_DEVICE_IP + ":" + port);
setLastMessagesPersistent(broker);
broker.start();

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

connection.start();

然后我尝试添加TransportListener:

((ActiveMQConnection) connection).addTransportListener(new TransportListener() {
    public void transportResumed() {
        System.out.println("resumed");
    }
    public void transportInterupted() {
        System.out.println("interrupted");
    }
    public void onException(IOException arg0) {
        System.out.println("ioexception: " + arg0);
    }
    public void onCommand(Object arg0) {
        System.out.println("command: " + arg0);
    }
});

我还注册了一个消费者和ProducerListener,如下所示:

Destination dest = session.createQueue(queuename);
MessageConsumer consumer = session.createConsumer(dest);

ProducerEventSource source = new ProducerEventSource(connection, dest);
System.out.println("Setting Producer Listener");
source.setProducerListener(prodevent -> {
    System.out.println("producer status: " + prodevent.isStarted());
});
// Gets called from inside the broker's Thread and somehow causes deadlocks if I don't invoke this from the outside
new Thread(() -> {
    try {
        consumer.setMessageListener(new NetworkEventPlayerAdapter(objectMapper, event, gameEventManager, playerID));
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

不幸的是,当我强行退出之前添加为生产者的另一个应用程序(Alt + F4)时,TransportListener和ProducerListener都没有给我任何输出。经纪人肯定会注意到:

 WARN | Transport Connection to: tcp://127.0.0.1:58988 failed: java.net.SocketException: Connection reset
 WARN | Transport Connection to: tcp://127.0.0.1:58986 failed: java.net.SocketException: Connection reset

但我找不到一种方法来获取Java中这些事件的回调。 我还尝试在代理中设置自定义IOExceptionHandler并向连接添加ExceptionListener。他们也从未被召唤过。

2 个答案:

答案 0 :(得分:1)

您可以使用咨询主题ActiveMQ.Advisory.Connection甚至ActiveMQ.Advisory.Producer.Queue ActiveMQ.Advisory.Producer.Topic,它们提供生产者数量连接的统计数据,请检查此链接{{3} }

答案 1 :(得分:0)

一种可能的方法是解析连接重置

的日志输出
  

警告|传输连接:tcp://127.0.0.1:58988失败:   java.net.SocketException:连接重置     警告|运输   连接到:tcp://127.0.0.1:58986失败:java.net.SocketException:   连接重置

因为套接字是在activemq中实现的,所以你必须在那里添加ExceptionListener来编写自己的异常处理例程......