use of com.rabbitmq.client.Envelope 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);
}
}
use of com.rabbitmq.client.Envelope 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;
}
use of com.rabbitmq.client.Envelope in project rabbitmq-java-client by rabbitmq.
the class TopologyRecoveryRetry method topologyRecoveryConsumerFailure.
@Test
public void topologyRecoveryConsumerFailure() throws Exception {
final String queue = "topology-recovery-retry-consumer-failure" + System.currentTimeMillis();
channel.queueDeclare(queue, false, false, true, new HashMap<>());
channel.queueBind(queue, "amq.topic", "topic1");
channel.queueBind(queue, "amq.topic", "topic2");
final CountDownLatch messagesReceivedLatch = new CountDownLatch(2);
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) {
messagesReceivedLatch.countDown();
}
});
final CountDownLatch recoveryLatch = new CountDownLatch(1);
((AutorecoveringConnection) connection).addRecoveryListener(new RecoveryListener() {
@Override
public void handleRecoveryStarted(Recoverable recoverable) {
// no-op
}
@Override
public void handleRecovery(Recoverable recoverable) {
recoveryLatch.countDown();
}
});
// we want recovery to fail when recovering the consumer
// give the recorded consumer a bad queue name so it fails
final RecordedConsumer consumer = ((AutorecoveringConnection) connection).getRecordedConsumers().values().iterator().next();
consumer.setQueue(UUID.randomUUID().toString());
// use the backoffConsumer to know that it has failed
// then delete the real queue & fix the recorded consumer
// it should fail once more because queue is gone, and then succeed
final CountDownLatch backoffLatch = new CountDownLatch(1);
backoffConsumer = attempt -> {
if (attempt == 1) {
consumer.setQueue(queue);
try {
Host.rabbitmqctl("delete_queue " + queue);
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
backoffLatch.countDown();
};
// close connection
Host.closeAllConnections();
// assert backoff was called
assertTrue(backoffLatch.await(90, TimeUnit.SECONDS));
// wait for full recovery
assertTrue(recoveryLatch.await(90, TimeUnit.SECONDS));
// publish messages to verify both bindings & consumer were recovered
basicPublishVolatile("test1".getBytes(), "amq.topic", "topic1");
basicPublishVolatile("test2".getBytes(), "amq.topic", "topic2");
assertTrue(messagesReceivedLatch.await(10, TimeUnit.SECONDS));
}
use of com.rabbitmq.client.Envelope in project rabbitmq-java-client by rabbitmq.
the class ExceptionHandling method testConsumerHandleConsumerException.
protected void testConsumerHandleConsumerException(ExceptionHandler eh, CountDownLatch latch, boolean expectChannelClose) throws InterruptedException, TimeoutException, IOException {
ConnectionFactory cf = newConnectionFactory(eh);
assertEquals(cf.getExceptionHandler(), eh);
Connection conn = cf.newConnection();
assertEquals(conn.getExceptionHandler(), eh);
Channel ch = conn.createChannel();
String q = ch.queueDeclare().getQueue();
ch.basicConsume(q, new DefaultConsumer(ch) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
throw new RuntimeException("exception expected here, don't freak out");
}
});
ch.basicPublish("", q, null, "".getBytes());
wait(latch);
assertEquals(!expectChannelClose, ch.isOpen());
}
use of com.rabbitmq.client.Envelope in project uavstack by uavorg.
the class TestRestService method testRabbitmq.
@POST
@Path("testRabbitmq")
public void testRabbitmq(String jsonString) {
String QUEUE_NAME = "haha";
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("10.100.66.81");
factory.setPort(5672);
try {
com.rabbitmq.client.Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
// System.out.println(" [x] Sent '" + message + "'");
channel.close();
conn.close();
com.rabbitmq.client.Connection connection = factory.newConnection();
Channel recvchannel = connection.createChannel();
recvchannel.queueDeclare(QUEUE_NAME, false, false, false, null);
com.rabbitmq.client.Consumer consumer = new DefaultConsumer(recvchannel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
Log.log(message);
// System.out.println(" [x] Received '" + message + "'1");
}
};
recvchannel.basicConsume(QUEUE_NAME, true, consumer);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
Aggregations