Search in sources :

Example 1 with CancelCallback

use of com.rabbitmq.client.CancelCallback in project hummer-framework by hummer-team.

the class RabbitMqConsumer method start.

public void start() throws IOException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException, TimeoutException {
    createConnection();
    channel = connection.createChannel();
    channel.queueDeclare(queueConfig.getQueueName(), queueConfig.isDurable(), queueConfig.isExclusive(), queueConfig.isAutoDelete(), queueConfig.getArguments());
    if (StringUtils.isNotEmpty(queueConfig.getRouteKey())) {
        channel.queueBind(queueConfig.getQueueName(), queueConfig.getExchange(), queueConfig.getRouteKey());
    }
    channel.addShutdownListener(new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException e) {
            if (!exitSignal) {
                log.warn("mq shutdown completed, reason is ", e);
            }
        }
    });
    channel.addReturnListener(new ReturnListener() {

        @Override
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
            log.info("consumer return {}", replyText);
        }
    });
    channel.basicQos(queueConfig.getQos());
    MqDeserializer mqDeserializer = DeserializerFactory.deserializer(queueConfig.getSerializerType());
    consumerTag = channel.basicConsume(queueConfig.getQueueName(), queueConfig.isAutoAck(), new DeliverCallback() {

        @Override
        public void handle(String consumerTag, Delivery message) throws IOException {
            T data;
            try {
                data = mqDeserializer.deserialize(message.getBody(), handler.messageType());
            } catch (Exception e) {
                log.error("deserialize message failed, topic is {} message type is {}", topic, handler.messageType(), e);
                return;
            }
            MessageData<T> messageData = new MessageData<>();
            messageData.setData(data);
            messageData.setQueueOffset(message.getEnvelope().getDeliveryTag());
            messageData.setProperties(Optional.ofNullable(message.getProperties().getHeaders()).orElse(Collections.emptyMap()).entrySet().stream().collect(Collectors.toConcurrentMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))));
            ListenableFuture<Long> future = ((ListeningExecutorService) executorService).submit(() -> handler.handlerAndReturnOffset(messageData));
            Futures.addCallback(future, new FutureCallback<>() {

                @Override
                public void onSuccess(@Nullable Long offset) {
                    ack(offset);
                }

                @Override
                public void onFailure(Throwable throwable) {
                    log.warn("business handler message failed {}", topic, throwable);
                }
            }, executorService);
        }
    }, new CancelCallback() {

        @Override
        public void handle(String consumerTag) throws IOException {
            log.warn("consumer cancel {}", consumerTag);
        }
    }, new ConsumerShutdownSignalCallback() {

        @Override
        public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
            log.warn("consumer shutdown {} ", consumerTag, sig);
        }
    });
    log.info("consumer {} start ok,queueConfig is {}", consumerTag, queueConfig);
}
Also used : ConsumerShutdownSignalCallback(com.rabbitmq.client.ConsumerShutdownSignalCallback) DeliverCallback(com.rabbitmq.client.DeliverCallback) ShutdownListener(com.rabbitmq.client.ShutdownListener) ReturnListener(com.rabbitmq.client.ReturnListener) ShutdownSignalException(com.rabbitmq.client.ShutdownSignalException) AMQP(com.rabbitmq.client.AMQP) CancelCallback(com.rabbitmq.client.CancelCallback) MqDeserializer(com.hummer.message.common.deserializer.MqDeserializer) MessageData(com.hummer.message.common.MessageData) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ShutdownSignalException(com.rabbitmq.client.ShutdownSignalException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Delivery(com.rabbitmq.client.Delivery)

Example 2 with CancelCallback

use of com.rabbitmq.client.CancelCallback 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 3 with CancelCallback

use of com.rabbitmq.client.CancelCallback 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)

Example 4 with CancelCallback

use of com.rabbitmq.client.CancelCallback 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)

Aggregations

CancelCallback (com.rabbitmq.client.CancelCallback)4 DeliverCallback (com.rabbitmq.client.DeliverCallback)4 IOException (java.io.IOException)4 AMQP (com.rabbitmq.client.AMQP)3 Channel (com.rabbitmq.client.Channel)3 Connection (com.rabbitmq.client.Connection)2 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)2 CIEnvironmentContributingAction (com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)2 MsgCheck (com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck)2 RabbitMQMessage (com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage)2 SendResult (com.redhat.jenkins.plugins.ci.messaging.data.SendResult)2 ProviderData (com.redhat.jenkins.plugins.ci.provider.data.ProviderData)2 RabbitMQPublisherProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData)2 RabbitMQSubscriberProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData)2 PluginUtils (com.redhat.utils.PluginUtils)2 EnvVars (hudson.EnvVars)2 Result (hudson.model.Result)2 Run (hudson.model.Run)2 TaskListener (hudson.model.TaskListener)2 StandardCharsets (java.nio.charset.StandardCharsets)2