Example usage for com.rabbitmq.client Channel waitForConfirms

List of usage examples for com.rabbitmq.client Channel waitForConfirms

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel waitForConfirms.

Prototype

boolean waitForConfirms() throws InterruptedException;

Source Link

Document

Wait until all messages published since the last call have been either ack'd or nack'd by the broker.

Usage

From source file:info.pancancer.arch3.worker.WorkerHeartbeat.java

License:Open Source License

@Override
public void run() {

    Channel reportingChannel = null;
    try {//from w  w  w  .j ava  2 s . co m
        try {
            reportingChannel = Utilities.setupExchange(settings, this.queueName);
        } catch (IOException | TimeoutException | AlreadyClosedException e) {
            LOG.error("Exception caught! Queue channel could not be opened, waiting. Exception is: "
                    + e.getMessage(), e);
            // retry after a minute, do not die simply because the launcher is unavailable, it may come back
            Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.info("Caught interrupt signal, heartbeat shutting down.", e);
        return;
    }

    LOG.info("starting heartbeat thread, will send heartbeat message ever " + secondsDelay + " seconds.");
    while (!Thread.interrupted()) {
        // byte[] stdOut = this.getMessageBody().getBytes(StandardCharsets.UTF_8);
        try {
            try {
                Status heartbeatStatus = new Status();
                heartbeatStatus.setJobUuid(this.jobUuid);
                heartbeatStatus.setMessage("job is running; IP address: " + networkID);
                heartbeatStatus.setState(StatusState.RUNNING);
                heartbeatStatus.setType(Utilities.JOB_MESSAGE_TYPE);
                heartbeatStatus.setVmUuid(this.vmUuid);
                heartbeatStatus.setIpAddress(networkID);

                // String stdOut = this.statusSource.getStdOut();
                Lock lock = new ReentrantLock();
                lock.lock();
                String stdOut = this.statusSource.getStdOut(stdoutSnipSize);
                String stdErr = this.statusSource.getStdErr();
                lock.unlock();
                heartbeatStatus.setStdout(stdOut);
                heartbeatStatus.setStderr(stdErr);
                String heartBeatMessage = heartbeatStatus.toJSON();
                LOG.debug("Sending heartbeat message to " + queueName + ", with body: " + heartBeatMessage);
                reportingChannel.basicPublish(queueName, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN,
                        heartBeatMessage.getBytes(StandardCharsets.UTF_8));
                reportingChannel.waitForConfirms();

                Thread.sleep((long) (secondsDelay * MILLISECONDS_PER_SECOND));
            } catch (IOException | AlreadyClosedException e) {
                LOG.error("IOException caught! Message may not have been published. Exception is: "
                        + e.getMessage(), e);
                // retry after a minute, do not die simply because the launcher is unavailable, it may come back
                Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
            }
        } catch (InterruptedException e) {
            LOG.info("Heartbeat shutting down.");
            if (reportingChannel.getConnection().isOpen()) {
                try {
                    reportingChannel.getConnection().close();
                } catch (IOException e1) {
                    LOG.error("Error closing reportingChannel connection: " + e1.getMessage(), e1);
                }
            }
            if (reportingChannel.isOpen()) {
                try {
                    reportingChannel.close();
                } catch (IOException e1) {
                    LOG.error("Error (IOException) closing reportingChannel: " + e1.getMessage(), e1);
                } catch (TimeoutException e1) {
                    LOG.error("Error (TimeoutException) closing reportingChannel: " + e1.getMessage(), e1);
                }
            }
            LOG.debug("reporting channel open: " + reportingChannel.isOpen());
            LOG.debug("reporting channel connection open: " + reportingChannel.getConnection().isOpen());

            Thread.currentThread().interrupt();
        }
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  ?./* w  ww. ja  v a 2  s . co m*/
 * <p>
 * exchange = fanout
 * ??? topic ?
 *
 * @param topic   
 * @param message ?
 * @param confirm ??
 * @return ???rabbit confirm ?????
 */
public boolean doPublish(String topic, String message, boolean confirm) {
    Connection connection = rabbitAdapter.getConnection();
    Channel channel = connection.createChannel(false);
    Object funResult = null;
    try {
        if (confirm) {
            channel.confirmSelect();
        }
        channel.exchangeDeclare(topic, BuiltinExchangeType.FANOUT, true);
        AMQP.BasicProperties properties = new AMQP.BasicProperties("text/plain", null, getMQHeader(topic), 2, 0,
                null, null, null, null, null, null, null, null, null);
        funResult = sendBeforeFun.invoke(topic, "", properties);
        channel.basicPublish(topic, "", properties, message.getBytes());
        if (confirm) {
            try {
                return channel.waitForConfirms();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("[MQ] Rabbit publish error.", e);
                sendErrorFun.invoke(e, funResult);
                return false;
            }
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error("[MQ] Rabbit publish error.", e);
        sendErrorFun.invoke(e, funResult);
        return false;
    } finally {
        try {
            channel.close();
            sendFinishFun.invoke(funResult);
        } catch (IOException | TimeoutException e) {
            logger.error("[MQ] Rabbit publish error.", e);
        }
        connection.close();
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  .//w  ww .  j a v a  2  s  . c om
 * <p>
 * exchange = fanout
 *
 * @param address ?
 * @param message ?
 * @param confirm ??
 * @return ??rabbit confirm ?????
 */
public boolean doRequest(String address, String message, boolean confirm) {
    Connection connection = rabbitAdapter.getConnection();
    Channel channel = connection.createChannel(false);
    Object funResult = null;
    try {
        if (confirm) {
            channel.confirmSelect();
        }
        channel.queueDeclare(address, true, false, false, null);
        AMQP.BasicProperties properties = new AMQP.BasicProperties("text/plain", null, getMQHeader(address), 2,
                0, null, null, null, null, null, null, null, null, null);
        funResult = sendBeforeFun.invoke("", address, properties);
        channel.basicPublish("", address, properties, message.getBytes());
        if (confirm) {
            try {
                return channel.waitForConfirms();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("[MQ] Rabbit request error.", e);
                sendErrorFun.invoke(e, funResult);
                return false;
            }
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error("[MQ] Rabbit request error.", e);
        sendErrorFun.invoke(e, funResult);
        return false;
    } finally {
        try {
            channel.close();
            sendFinishFun.invoke(funResult);
        } catch (IOException | TimeoutException e) {
            logger.error("[MQ] Rabbit request error.", e);
        }
        connection.close();
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  ?.//from  w w  w  . j av  a 2s.com
 * <p>
 * exchange = topic
 *
 * @param topic      
 * @param routingKey Key
 * @param queueName  ??
 * @param message    ?
 * @param confirm    ??
 * @return ???rabbit confirm ?????
 */
public boolean publishWithTopic(String topic, String routingKey, String queueName, String message,
        boolean confirm) {
    logger.trace("[MQ] publishWithTopic {}:{}", topic, message);
    Connection connection = rabbitAdapter.getConnection();
    Channel channel = connection.createChannel(false);
    Object funResult = null;
    try {
        if (confirm) {
            channel.confirmSelect();
        }
        channel.queueDeclare(queueName, true, false, false, null);
        channel.exchangeDeclare(topic, BuiltinExchangeType.TOPIC, true);
        AMQP.BasicProperties properties = new AMQP.BasicProperties("text/plain", null, getMQHeader(topic), 2, 0,
                null, null, null, null, null, null, null, null, null);
        funResult = sendBeforeFun.invoke(topic, routingKey, properties);
        channel.basicPublish(topic, routingKey, properties, message.getBytes());
        if (confirm) {
            try {
                return channel.waitForConfirms();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("[MQ] Rabbit publishWithTopic error.", e);
                sendErrorFun.invoke(e, funResult);
                return false;
            }
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error("[MQ] Rabbit publishWithTopic error.", e);
        sendErrorFun.invoke(e, funResult);
        return false;
    } finally {
        try {
            channel.close();
            sendFinishFun.invoke(funResult);
        } catch (IOException | TimeoutException e) {
            logger.error("[MQ] Rabbit publishWithTopic error.", e);
        }
        connection.close();
    }
}

From source file:org.axonframework.amqp.eventhandling.spring.SpringAMQPPublisherTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_UnitOfWorkCommitted()
        throws InterruptedException, IOException, TimeoutException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);
    testSubject.setPublisherAckTimeout(123);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.isOpen()).thenReturn(true);
    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class))
            .thenReturn(new SimpleSerializedObject<>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<>(new byte[0], byte[].class));

    UnitOfWork<?> uow = DefaultUnitOfWork.startAndGet(message);

    eventBus.publish(message);//  ww  w. j a v a 2  s.  c o  m
    verify(channel, never()).waitForConfirms();

    uow.commit();

    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie(123);
    verify(channel, never()).txSelect();
    verify(channel, never()).txCommit();
    verify(channel, never()).txRollback();
}

From source file:org.axonframework.amqp.eventhandling.spring.SpringAMQPPublisherTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_NoActiveUnitOfWork() throws InterruptedException, IOException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class))
            .thenReturn(new SimpleSerializedObject<>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<>(new byte[0], byte[].class));

    eventBus.publish(message);/*from  www  .j  a  v  a 2  s. c  o  m*/
    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie();
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPEventBusTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_UnitOfWorkCommitted()
        throws InterruptedException, IOException, TimeoutException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);
    testSubject.setPublisherAckTimeout(123);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.isOpen()).thenReturn(true);
    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class))
            .thenReturn(new SimpleSerializedObject<>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<>(new byte[0], byte[].class));

    UnitOfWork<?> uow = DefaultUnitOfWork.startAndGet(message);

    testSubject.publish(message);//www  .j a  v  a2s .co m
    verify(channel, never()).waitForConfirms();

    uow.commit();

    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie(123);
    verify(channel, never()).txSelect();
    verify(channel, never()).txCommit();
    verify(channel, never()).txRollback();
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPEventBusTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_NoActiveUnitOfWork() throws InterruptedException, IOException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class))
            .thenReturn(new SimpleSerializedObject<>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<>(new byte[0], byte[].class));

    testSubject.publish(message);/*from  w w  w  .j  a va 2  s  . co  m*/
    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie();
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPTerminalTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_UnitOfWorkCommitted()
        throws InterruptedException, IOException, TimeoutException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);
    testSubject.setPublisherAckTimeout(123);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<String>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class)).thenReturn(
            new SimpleSerializedObject<byte[]>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<byte[]>(new byte[0], byte[].class));

    UnitOfWork uow = DefaultUnitOfWork.startAndGet();

    testSubject.publish(message);/*from   w  ww.  j a v  a2  s. com*/
    verify(channel, never()).waitForConfirms();

    uow.commit();

    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie(123);
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPTerminalTest.java

License:Apache License

@Test
public void testSendMessageWithPublisherAck_NoActiveUnitOfWork() throws InterruptedException, IOException {
    testSubject.setTransactional(false);
    testSubject.setWaitForPublisherAck(true);

    Connection connection = mock(Connection.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    Channel channel = mock(Channel.class);

    when(channel.waitForConfirms()).thenReturn(true);
    when(connection.createChannel(false)).thenReturn(channel);
    GenericEventMessage<String> message = new GenericEventMessage<String>("Message");
    when(serializer.serialize(message.getPayload(), byte[].class)).thenReturn(
            new SimpleSerializedObject<byte[]>("Message".getBytes(UTF_8), byte[].class, "String", "0"));
    when(serializer.serialize(message.getMetaData(), byte[].class))
            .thenReturn(new SerializedMetaData<byte[]>(new byte[0], byte[].class));

    testSubject.publish(message);/*ww w.j a  v a 2 s  . c o  m*/
    verify(channel).confirmSelect();
    verify(channel).basicPublish(eq("mockExchange"), eq("java.lang"), eq(false), eq(false),
            any(AMQP.BasicProperties.class), isA(byte[].class));
    verify(channel).waitForConfirmsOrDie();
}