Search in sources :

Example 46 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project jms-messaging-plugin by jenkinsci.

the class RabbitMQMessagingWorker method subscribe.

@Override
public boolean subscribe(String jobname, String selector) {
    if (interrupt) {
        return true;
    }
    if (this.topic != null) {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (connection == null || !connection.isOpen()) {
                    if (!connect()) {
                        return false;
                    }
                }
                if (channel == null || !channel.isOpen()) {
                    this.channel = connection.createChannel();
                    log.info("Subscribing job '" + jobname + "' to " + this.topic + " topic.");
                    String queueName = getQueue(provider);
                    try {
                        // Check if queue exists
                        channel.queueDeclarePassive(queueName);
                    } catch (IOException e) {
                        // Request new queue - durable false, exclusive true, autodelete true
                        this.channel = connection.createChannel();
                        channel.queueDeclare(queueName, false, true, true, null);
                    }
                    channel.exchangeDeclarePassive(exchangeName);
                    channel.queueBind(queueName, exchangeName, this.topic);
                    // Create deliver callback to listen for messages
                    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                        String json = new String(delivery.getBody(), StandardCharsets.UTF_8);
                        log.info("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
                        RabbitMQMessage message = new RabbitMQMessage(delivery.getEnvelope().getRoutingKey(), json, delivery.getProperties().getMessageId());
                        message.setTimestamp(new Date().getTime());
                        message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
                        messageQueue.add(message);
                    };
                    this.consumerTag = channel.basicConsume(queueName, deliverCallback, (CancelCallback) null);
                    log.info("Successfully subscribed job '" + jobname + "' to topic '" + this.topic + "'.");
                } else {
                    log.info("Already subscribed job '" + jobname + "' to topic '" + this.topic + "'.");
                }
                return true;
            } catch (Exception ex) {
                // Either we were interrupted, or something else went
                // wrong. If we were interrupted, then we will jump ship
                // on the next iteration. If something else happened,
                // then we just unsubscribe here, sleep, so that we may
                // try again on the next iteration.
                log.log(Level.SEVERE, "Eexception raised while subscribing job '" + jobname + "', retrying in " + RETRY_MINUTES + " minutes.", ex);
                if (!Thread.currentThread().isInterrupted()) {
                    unsubscribe(jobname);
                    try {
                        Thread.sleep(RETRY_MINUTES * 60 * 1000);
                    } catch (InterruptedException ie) {
                        // We were interrupted while waiting to retry.
                        // We will jump ship on the next iteration.
                        // NB: The interrupt flag was cleared when
                        // InterruptedException was thrown. We have to
                        // re-install it to make sure we eventually
                        // leave this thread.
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }
    return false;
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) Date(java.util.Date) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) ZonedDateTime(java.time.ZonedDateTime) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) HashMap(java.util.HashMap) Connection(com.rabbitmq.client.Connection) StringUtils(org.apache.commons.lang3.StringUtils) Level(java.util.logging.Level) CancelCallback(com.rabbitmq.client.CancelCallback) Map(java.util.Map) EnvVars(hudson.EnvVars) TaskListener(hudson.model.TaskListener) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) RabbitMQPublisherProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData) Jenkins(jenkins.model.Jenkins) ExceptionUtils(org.apache.commons.lang.exception.ExceptionUtils) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) MsgCheck(com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck) PluginUtils(com.redhat.utils.PluginUtils) IOException(java.io.IOException) UUID(java.util.UUID) Logger(java.util.logging.Logger) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) TimeUnit(java.util.concurrent.TimeUnit) Result(hudson.model.Result) Channel(com.rabbitmq.client.Channel) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction) ProviderData(com.redhat.jenkins.plugins.ci.provider.data.ProviderData) AMQP(com.rabbitmq.client.AMQP) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CancelCallback(com.rabbitmq.client.CancelCallback) DeliverCallback(com.rabbitmq.client.DeliverCallback) IOException(java.io.IOException) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) Date(java.util.Date) IOException(java.io.IOException)

Example 47 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.

the class ReceiveLogs 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, "fanout");
    // 临时队列
    String queueName = channel.queueDeclare().getQueue();
    // 绑定
    channel.queueBind(queueName, EXCHANGE_NAME, "");
    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 '" + message + "'");
        print2File(message);
    };
    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
    });
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) Connection(com.rabbitmq.client.Connection) Channel(com.rabbitmq.client.Channel) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Example 48 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.

the class ReceiveLogsDirect 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();
    // 交换机的类型 DIRECT
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
    String queueName = channel.queueDeclare().getQueue();
    // 所有日志严重性级别
    String[] severities = { "error" };
    // String[] severities = {"error", "info", "warning"};
    for (String severity : severities) {
        // 关注所有级别的日志(多重绑定)
        channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }
    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 + "'");
        print2File(message);
    };
    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
    });
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) Connection(com.rabbitmq.client.Connection) Channel(com.rabbitmq.client.Channel) BuiltinExchangeType(com.rabbitmq.client.BuiltinExchangeType) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Example 49 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.

the class MsgReceiver method main.

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    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 '" + message + "'");
    };
    channel.basicConsume(QUEUE_NAME, 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 50 with DeliverCallback

use of com.rabbitmq.client.DeliverCallback in project SpringBoot-Learning by kong0827.

the class consumer01 method main.

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("47.102.218.26");
    factory.setPort(5672);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    /**
     * 注意
     * Rabbitmq服务通道是持久通道,该queue 已经存在, 而且通道属性需要保持一致
     */
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    // DefaultConsumer consumer = new DefaultConsumer(channel) {
    // /**
    // *
    // * @param consumerTag 标识
    // * @param envelope 获取的一些信息 包括交换机 路由
    // * @param properties 配置信息
    // * @param body 数据
    // * @throws IOException
    // */
    // @Override
    // public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    // System.out.println("consumerTag:" + consumerTag);
    // System.out.println("envelope:" + envelope);
    // System.out.println("properties:" + properties);
    // System.out.println("message:" + new String(body));
    // }
    // };
    // channel.basicConsume(QUEUE_NAME, true, consumer);
    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" message: " + message + "'");
    };
    /**
     * 启动一个消费者,并返回服务端生成的消费者标识
     * queue:队列名
     * autoAck:true 接收到传递过来的消息后acknowledged(应答服务器),false 接收到消息后不应答服务器
     * deliverCallback: 当一个消息发送过来后的回调接口
     * cancelCallback:当一个消费者取消订阅时的回调接口;取消消费者订阅队列时除了使用{@link Channel#basicCancel}之外的所有方式都会调用该回调方法
     * @return 服务端生成的消费者标识
     */
    channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
    });
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) 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)

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