Search in sources :

Example 6 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project canal by alibaba.

the class CanalRabbitMQConsumer method connect.

@Override
public void connect() {
    ConnectionFactory factory = new ConnectionFactory();
    if (accessKey.length() > 0 && secretKey.length() > 0) {
        factory.setCredentialsProvider(new AliyunCredentialsProvider(accessKey, secretKey, resourceOwnerId));
    } else {
        factory.setUsername(username);
        factory.setPassword(password);
    }
    // 解析出端口 modified by 16075140
    if (nameServer != null && nameServer.contains(":")) {
        String[] serverHostAndPort = nameServer.split(":");
        factory.setHost(serverHostAndPort[0]);
        factory.setPort(Integer.parseInt(serverHostAndPort[1]));
    } else {
        factory.setHost(nameServer);
    }
    factory.setAutomaticRecoveryEnabled(true);
    factory.setNetworkRecoveryInterval(5000);
    factory.setVirtualHost(vhost);
    try {
        connect = factory.newConnection();
        channel = connect.createChannel();
    } catch (IOException | TimeoutException e) {
        throw new CanalClientException("Start RabbitMQ producer error", e);
    }
    // 不存在连接 则重新连接
    if (connect == null) {
        this.connect();
    }
    Consumer consumer = new DefaultConsumer(channel) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            if (body != null) {
                channel.basicAck(envelope.getDeliveryTag(), process(body));
            }
        }
    };
    try {
        channel.basicConsume(queueName, false, consumer);
    } catch (IOException e) {
        throw new CanalClientException("error", e);
    }
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) CanalMsgConsumer(com.alibaba.otter.canal.connector.core.spi.CanalMsgConsumer) Consumer(com.rabbitmq.client.Consumer) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) CanalClientException(com.alibaba.otter.canal.protocol.exception.CanalClientException) AliyunCredentialsProvider(com.alibaba.otter.canal.connector.rabbitmq.producer.AliyunCredentialsProvider) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project cosmic by MissionCriticalCloud.

the class RabbitMQEventBus method subscribe.

/**
 * Call to subscribe to interested set of events
 *
 * @param topic      defines category and type of the events being subscribed to
 * @param subscriber subscriber that intends to receive event notification
 * @return UUID that represents the subscription with event bus
 * @throws EventBusException
 */
@Override
public UUID subscribe(final EventTopic topic, final EventSubscriber subscriber) throws EventBusException {
    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }
    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    final UUID queueId = UUID.randomUUID();
    final String queueName = queueId.toString();
    try {
        final String bindingKey = createBindingKey(topic);
        // store the subscriber details before creating channel
        s_subscribers.put(queueName, new Ternary<>(bindingKey, null, subscriber));
        // create a channel dedicated for this subscription
        final Connection connection = getConnection();
        final Channel channel = createChannel(connection);
        // create a queue and bind it to the exchange with binding key formed from event topic
        createExchange(channel, amqpExchangeName);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, amqpExchangeName, bindingKey);
        // register a callback handler to receive the events that a subscriber subscribed to
        channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException {
                RabbitMQEventBus.this.handleDelivery(queueName, envelope, body);
            }
        });
        // update the channel details for the subscription
        final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        queueDetails.second(channel);
        s_subscribers.put(queueName, queueDetails);
    } catch (final AlreadyClosedException | ConnectException | NoSuchAlgorithmException | KeyManagementException | TimeoutException e) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", e);
    } catch (final IOException e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage(), e);
    }
    return queueId;
}
Also used : EventSubscriber(com.cloud.framework.events.EventSubscriber) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Envelope(com.rabbitmq.client.Envelope) KeyManagementException(java.security.KeyManagementException) AMQP(com.rabbitmq.client.AMQP) EventBusException(com.cloud.framework.events.EventBusException) UUID(java.util.UUID) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project rabbitmq-java-client by rabbitmq.

the class ConsumerCancelNotification method consumerCancellationNotification.

@Test
public void consumerCancellationNotification() throws IOException, InterruptedException {
    final BlockingQueue<Boolean> result = new ArrayBlockingQueue<Boolean>(1);
    channel.queueDeclare(queue, false, true, false, null);
    Consumer consumer = new DefaultConsumer(channel) {

        @Override
        public void handleCancel(String consumerTag) throws IOException {
            try {
                result.put(true);
            } catch (InterruptedException e) {
                fail();
            }
        }
    };
    channel.basicConsume(queue, consumer);
    channel.queueDelete(queue);
    assertTrue(result.take());
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Consumer(com.rabbitmq.client.Consumer) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Test(org.junit.Test)

Example 9 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project rabbitmq-java-client by rabbitmq.

the class Confirm method setUp.

@Override
public void setUp() throws IOException, TimeoutException {
    super.setUp();
    channel.confirmSelect();
    channel.queueDeclare("confirm-test", true, true, false, null);
    channel.queueDeclare("confirm-durable-nonexclusive", true, false, false, null);
    channel.basicConsume("confirm-test", true, new DefaultConsumer(channel));
    channel.queueDeclare("confirm-test-nondurable", false, true, false, null);
    channel.basicConsume("confirm-test-nondurable", true, new DefaultConsumer(channel));
    channel.queueDeclare("confirm-test-noconsumer", true, true, false, null);
    channel.queueDeclare("confirm-test-2", true, true, false, null);
    channel.basicConsume("confirm-test-2", true, new DefaultConsumer(channel));
    channel.queueBind("confirm-test", "amq.direct", "confirm-multiple-queues");
    channel.queueBind("confirm-test-2", "amq.direct", "confirm-multiple-queues");
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer)

Example 10 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project rabbitmq-java-client by rabbitmq.

the class ConsumerCount method consumerCount.

@Test
public void consumerCount() throws IOException {
    String q = generateQueueName();
    channel.queueDeclare(q, false, true, false, null);
    assertEquals(0, channel.consumerCount(q));
    String tag = channel.basicConsume(q, new DefaultConsumer(channel));
    assertEquals(1, channel.consumerCount(q));
    channel.basicCancel(tag);
    assertEquals(0, channel.consumerCount(q));
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Test(org.junit.Test)

Aggregations

DefaultConsumer (com.rabbitmq.client.DefaultConsumer)32 IOException (java.io.IOException)21 Envelope (com.rabbitmq.client.Envelope)20 Channel (com.rabbitmq.client.Channel)15 Test (org.junit.Test)15 AMQP (com.rabbitmq.client.AMQP)11 TimeoutException (java.util.concurrent.TimeoutException)10 Connection (com.rabbitmq.client.Connection)9 Consumer (com.rabbitmq.client.Consumer)9 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)3 AutorecoveringConnection (com.rabbitmq.client.impl.recovery.AutorecoveringConnection)3 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UUID (java.util.UUID)3 Path (javax.ws.rs.Path)3 AlreadyClosedException (com.rabbitmq.client.AlreadyClosedException)2 Recoverable (com.rabbitmq.client.Recoverable)2 RecoveryListener (com.rabbitmq.client.RecoveryListener)2