Search in sources :

Example 11 with DeliverCallback

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

the class RabbitMQMessagingWorker method waitForMessage.

@Override
public String waitForMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
    RabbitMQSubscriberProviderData pd = (RabbitMQSubscriberProviderData) pdata;
    try {
        if (connection == null || !connection.isOpen()) {
            connect();
        }
        if (channel == null || !channel.isOpen()) {
            this.channel = connection.createChannel();
        }
        channel.exchangeDeclarePassive(exchangeName);
        channel.queueBind(getQueue(provider), exchangeName, this.topic);
    } catch (Exception ex) {
        log.severe("Connection to broker can't be established!");
        log.severe(ExceptionUtils.getStackTrace(ex));
        listener.error("Connection to broker can't be established!");
        listener.error(ExceptionUtils.getStackTrace(ex));
        return null;
    }
    log.info("Waiting for message.");
    listener.getLogger().println("Waiting for message.");
    for (MsgCheck msgCheck : pd.getChecks()) {
        log.info(" with check: " + msgCheck.toString());
        listener.getLogger().println(" with check: " + msgCheck);
    }
    Integer timeout = (pd.getTimeout() != null ? pd.getTimeout() : RabbitMQSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES);
    log.info(" with timeout: " + timeout + " minutes");
    listener.getLogger().println(" with timeout: " + timeout + " minutes");
    // Create deliver callback to listen for messages
    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String json = new String(delivery.getBody(), StandardCharsets.UTF_8);
        listener.getLogger().println("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
        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);
    };
    String consumerTag = null;
    long startTime = new Date().getTime();
    int timeoutInMs = timeout * 60 * 1000;
    try {
        consumerTag = channel.basicConsume(getQueue(provider), deliverCallback, (CancelCallback) null);
        while ((new Date().getTime() - startTime) < timeoutInMs) {
            if (!messageQueue.isEmpty()) {
                RabbitMQMessage message = messageQueue.poll();
                log.info("Obtained message from queue: " + message.toJson());
                if (!provider.verify(message.getBodyJson(), pd.getChecks(), jobname)) {
                    channel.basicAck(message.getDeliveryTag(), false);
                    continue;
                }
                listener.getLogger().println("Message: '" + message.getMsgId() + "' was succesfully checked.");
                if (build != null) {
                    if (StringUtils.isNotEmpty(pd.getVariable())) {
                        EnvVars vars = new EnvVars();
                        vars.put(pd.getVariable(), message.getBodyJson());
                        build.addAction(new CIEnvironmentContributingAction(vars));
                    }
                }
                channel.basicAck(message.getDeliveryTag(), false);
                return message.getBodyJson();
            }
            if (interrupt) {
                return null;
            }
            TimeUnit.MILLISECONDS.sleep(500);
        }
        log.severe("Timed out waiting for message!");
        listener.getLogger().println("Timed out waiting for message!");
    } catch (Exception e) {
        // for more info
        if (e.getClass() == InterruptedException.class) {
            Thread.currentThread().interrupt();
        }
        log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
    } finally {
        try {
            if (consumerTag != null) {
                channel.basicCancel(consumerTag);
            }
            channel.close();
        } catch (Exception e) {
            listener.getLogger().println("exception in finally");
        }
    }
    return null;
}
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) DeliverCallback(com.rabbitmq.client.DeliverCallback) MsgCheck(com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck) IOException(java.io.IOException) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) Date(java.util.Date) EnvVars(hudson.EnvVars) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) CancelCallback(com.rabbitmq.client.CancelCallback) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)

Example 12 with DeliverCallback

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

the class RPCServer method main.

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try (Connection connection = factory.newConnection();
        Channel channel = connection.createChannel()) {
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.queuePurge(RPC_QUEUE_NAME);
        channel.basicQos(1);
        System.out.println(" [x] Awaiting RPC requests");
        Object monitor = new Object();
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(delivery.getProperties().getCorrelationId()).build();
            String response = "";
            try {
                String message = new String(delivery.getBody(), "UTF-8");
                int n = Integer.parseInt(message);
                System.out.println(" [.] fib(" + message + ")");
                response += fib(n);
            } catch (RuntimeException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicPublish("", delivery.getProperties().getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                // RabbitMq consumer worker thread notifies the RPC server owner thread
                synchronized (monitor) {
                    monitor.notify();
                }
            }
        };
        channel.basicConsume(RPC_QUEUE_NAME, false, deliverCallback, (consumerTag -> {
        }));
        // Wait and be prepared to consume the message from RPC client.
        while (true) {
            synchronized (monitor) {
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Connection(com.rabbitmq.client.Connection) Channel(com.rabbitmq.client.Channel) AMQP(com.rabbitmq.client.AMQP) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) DeliverCallback(com.rabbitmq.client.DeliverCallback)

Example 13 with DeliverCallback

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

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();
    // 关注所有的授权日志、所有info和waring级别的日志
    String[] bindingKeys = { "auth.*", "*.info", "#.warning" };
    for (String bindingKey : bindingKeys) {
        // 关注所有级别的日志(多重绑定)
        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 14 with DeliverCallback

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

the class ReceiveLogsTopic2 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();
    // 只关注核心错误级别的日志,然后记录到文件中去
    String severity = "kern.error";
    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");
        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 15 with DeliverCallback

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

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();
    // 持久化
    boolean durable = true;
    channel.queueDeclare(TASK_QUEUE_NAME, durable, 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)

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