Search in sources :

Example 41 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project rabbitmq-tutorials by rabbitmq.

the class ReceiveLogsTopic method main.

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(EXCHANGE_NAME, "topic");
    String queueName = channel.queueDeclare().getQueue();
    if (argv.length < 1) {
        System.err.println("Usage: ReceiveLogsTopic [binding_key]...");
        System.exit(1);
    }
    for (String bindingKey : argv) {
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
    };
    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
    });
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Connection(com.rabbitmq.client.Connection) Channel(com.rabbitmq.client.Channel) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Example 42 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project rabbitmq-tutorials by rabbitmq.

the class Worker method main.

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    channel.basicQos(1);
    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
        try {
            doWork(message);
        } finally {
            System.out.println(" [x] Done");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> {
    });
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Connection(com.rabbitmq.client.Connection) Channel(com.rabbitmq.client.Channel) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Example 43 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project quarkus-quickstarts by quarkusio.

the class QuoteProcessorTest method testProcessor.

@Test
void testProcessor() throws Exception {
    String quoteId = UUID.randomUUID().toString();
    Channel channel = getChannel();
    channel.exchangeDeclare("quotes", TOPIC, true, false, Map.of());
    String queue = channel.queueDeclare("quotes", true, false, false, Map.of()).getQueue();
    channel.queueBind(queue, "quotes", "#");
    AtomicReference<Quote> receivedQuote = new AtomicReference<>(null);
    DeliverCallback deliverCallback = (consumerTag, message) -> {
        Quote quote = objectMapper.readValue(message.getBody(), Quote.class);
        if (!Objects.equals(quote.id, quoteId)) {
            return;
        }
        receivedQuote.set(quote);
    };
    String consumerTag = channel.basicConsume(queue, true, deliverCallback, tag -> {
    });
    AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().contentType("text/plain").build();
    channel.basicPublish("quote-requests", quoteId, props, quoteId.getBytes(UTF_8));
    await().atMost(3, SECONDS).untilAtomic(receivedQuote, notNullValue());
    channel.basicCancel(consumerTag);
}
Also used : Quote(org.acme.rabbitmq.model.Quote) Awaitility.await(org.awaitility.Awaitility.await) DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TOPIC(com.rabbitmq.client.BuiltinExchangeType.TOPIC) UUID(java.util.UUID) Connection(com.rabbitmq.client.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) Map(java.util.Map) Channel(com.rabbitmq.client.Channel) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Quote(org.acme.rabbitmq.model.Quote) AMQP(com.rabbitmq.client.AMQP) AMQP(com.rabbitmq.client.AMQP) Channel(com.rabbitmq.client.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) DeliverCallback(com.rabbitmq.client.DeliverCallback) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Test(org.junit.jupiter.api.Test)

Example 44 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project mt-auth by publicdevop2019.

the class RabbitMQEventStreamService method subscribe.

@Override
public void subscribe(String subscribedApplicationName, boolean internal, @Nullable String fixedQueueName, Consumer<StoredEvent> consumer, String... topics) {
    String routingKeyWithoutTopic = subscribedApplicationName + "." + (internal ? "internal" : "external") + ".";
    String queueName;
    if (fixedQueueName != null) {
        queueName = fixedQueueName;
    } else {
        long id = CommonDomainRegistry.getUniqueIdGeneratorService().id();
        queueName = Long.toString(id, 36);
    }
    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        log.trace("mq message received");
        String s = new String(delivery.getBody(), StandardCharsets.UTF_8);
        StoredEvent event = CommonDomainRegistry.getCustomObjectSerializer().deserialize(s, StoredEvent.class);
        log.debug("handling {} with id {}", ClassUtility.getShortName(event.getName()), event.getId());
        try {
            consumer.accept(event);
        } catch (Exception ex) {
            log.error("error during consume, catch error to maintain connection", ex);
        }
        log.trace("mq message consumed");
    };
    try {
        Channel channel = connectionSub.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
        checkExchange(channel);
        for (String topic : topics) {
            channel.queueBind(queueName, EXCHANGE_NAME, routingKeyWithoutTopic + topic);
        }
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    } catch (IOException e) {
        log.error("unable create queue for {} with routing key {} and queue name {}", subscribedApplicationName, routingKeyWithoutTopic, queueName, e);
    }
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) SagaEventStreamService(com.mt.common.domain.model.domain_event.SagaEventStreamService) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) CommonDomainRegistry(com.mt.common.domain.CommonDomainRegistry) Resource(javax.annotation.Resource) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) Connection(com.rabbitmq.client.Connection) StandardCharsets(java.nio.charset.StandardCharsets) StoredEvent(com.mt.common.domain.model.domain_event.StoredEvent) Value(org.springframework.beans.factory.annotation.Value) Consumer(java.util.function.Consumer) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) Environment(org.springframework.core.env.Environment) ClassUtility(com.mt.common.domain.model.clazz.ClassUtility) EXCHANGE_NAME(com.mt.common.CommonConstant.EXCHANGE_NAME) MQHelper(com.mt.common.domain.model.domain_event.MQHelper) Channel(com.rabbitmq.client.Channel) Nullable(javax.annotation.Nullable) Channel(com.rabbitmq.client.Channel) DeliverCallback(com.rabbitmq.client.DeliverCallback) StoredEvent(com.mt.common.domain.model.domain_event.StoredEvent) IOException(java.io.IOException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException)

Example 45 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project Iot-now-start by Dongboy111.

the class Work01 method main.

public static void main(String[] args) throws IOException, TimeoutException {
    Channel channel = RabbitMqUtils.getChannel();
    // 声明接受消息
    DeliverCallback deliverCallback = (consumerTag, message) -> {
        System.out.println("接受到的消息:" + new String(message.getBody()));
    };
    // 取消消息消费
    CancelCallback cancelCallback = cousumerTag -> {
        System.out.println("消费被中断");
    };
    System.out.println("C2等到接收消息,,,,");
    channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
// 不关闭的话一直等待
}
Also used : RabbitMqUtils(com.ydh.rabbitmq.utils.RabbitMqUtils) CancelCallback(com.rabbitmq.client.CancelCallback) DeliverCallback(com.rabbitmq.client.DeliverCallback) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) Channel(com.rabbitmq.client.Channel) Channel(com.rabbitmq.client.Channel) CancelCallback(com.rabbitmq.client.CancelCallback) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Aggregations

DeliverCallback (com.rabbitmq.client.DeliverCallback)59 Channel (com.rabbitmq.client.Channel)58 Connection (com.rabbitmq.client.Connection)53 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)50 StandardCharsets (java.nio.charset.StandardCharsets)21 IOException (java.io.IOException)18 TimeoutException (java.util.concurrent.TimeoutException)12 ConnectionFactoryUtils (com.hyf.testDemo.mq.ConnectionFactoryUtils)11 AMQP (com.rabbitmq.client.AMQP)9 Map (java.util.Map)6 TimeUnit (java.util.concurrent.TimeUnit)6 Date (java.util.Date)5 RabbitMQUtils (com.quan.framework.amqp.util.RabbitMQUtils)4 CancelCallback (com.rabbitmq.client.CancelCallback)4 AbstractClient (ProducerDummy.Client.AbstractClient)3 AggregateMessage (ProducerDummy.Messages.AggregateMessage)2 Message (ProducerDummy.Messages.Message)2 ThreadUtil (cn.hutool.core.thread.ThreadUtil)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 DeclareOk (com.rabbitmq.client.AMQP.Exchange.DeclareOk)2