Search in sources :

Example 1 with MessageData

use of com.hummer.message.common.MessageData in project hummer-framework by hummer-team.

the class KafkaConsumerTaskHolder method readMessage.

private Tuple.TupleTwo<List<MessageData<E>>, List<RecordOffsetMetadata>> readMessage(final ConsumerRecords<String, Bytes> records) {
    int size = records.count();
    List<MessageData<E>> messageList = Lists.newArrayListWithCapacity(size);
    List<RecordOffsetMetadata> offsetList = Lists.newArrayListWithCapacity(size);
    MqDeserializer deserializer = DeserializerFactory.deserializer(ConsumerProperties.getDeserializerType());
    Iterator<ConsumerRecord<String, Bytes>> recordIterator = records.iterator();
    while (recordIterator.hasNext()) {
        ConsumerRecord<String, Bytes> recordItem = recordIterator.next();
        if (recordItem != null) {
            // message append list
            try {
                E e = deserializer.deserialize(recordItem.value().get(), this.metadata.getMessageHandler().messageType(), recordItem.topic());
                MessageData<E> messageData = new MessageData<>();
                messageData.setData(e);
                messageData.setQueueOffset(recordItem.offset());
                messageData.setQueueId(recordItem.partition());
                messageData.setProperties(headerToMap(recordItem.headers()));
                messageList.add(messageData);
            } catch (Exception e) {
                LOGGER.warn("topic {} message deserialize {} error ", metadata.getTopicId(), deserializer, e);
            }
            // offset append list if enable batch commit
            if (metadata.getCommitBatchSize() > 0) {
                offsetList.add(RecordOffsetMetadata.builder().offset(recordItem.offset()).topicId(recordItem.topic()).partition(recordItem.partition()).build());
            }
        }
    }
    return new Tuple.TupleTwo<>(messageList, offsetList);
}
Also used : MessageData(com.hummer.message.common.MessageData) MqDeserializer(com.hummer.message.common.deserializer.MqDeserializer) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) WakeupException(org.apache.kafka.common.errors.WakeupException) Bytes(org.apache.kafka.common.utils.Bytes)

Example 2 with MessageData

use of com.hummer.message.common.MessageData 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 3 with MessageData

use of com.hummer.message.common.MessageData in project hummer-framework by hummer-team.

the class MessageHandlerHolder method builderEventData.

public Tuple.TupleTwo<List<MessageData<E>>, List<MessageOffset>> builderEventData(List<MessageExt> msgs, String group) {
    List<MessageData<E>> data = Lists.newArrayListWithCapacity(msgs.size());
    List<MessageOffset> offsets = Lists.newArrayListWithCapacity(msgs.size());
    for (MessageExt message : msgs) {
        // event data
        try {
            MessageData<E> messageData = createEventData(message);
            data.add(messageData);
        } catch (Exception e) {
            LOGGER.warn("topic {} message deserialize error ", message.getTopic(), e);
        }
        // queue offset
        MessageOffset offset = getMessageOffset(message, group);
        offsets.add(offset);
    }
    return new Tuple.TupleTwo<>(data, offsets);
}
Also used : MessageExt(org.apache.rocketmq.common.message.MessageExt) MessageData(com.hummer.message.common.MessageData) MessageOffset(com.hummer.rocketmq.consumer.plugin.support.offset.MessageOffset)

Aggregations

MessageData (com.hummer.message.common.MessageData)3 MqDeserializer (com.hummer.message.common.deserializer.MqDeserializer)2 ListeningExecutorService (com.google.common.util.concurrent.ListeningExecutorService)1 MessageOffset (com.hummer.rocketmq.consumer.plugin.support.offset.MessageOffset)1 AMQP (com.rabbitmq.client.AMQP)1 AlreadyClosedException (com.rabbitmq.client.AlreadyClosedException)1 CancelCallback (com.rabbitmq.client.CancelCallback)1 ConsumerShutdownSignalCallback (com.rabbitmq.client.ConsumerShutdownSignalCallback)1 DeliverCallback (com.rabbitmq.client.DeliverCallback)1 Delivery (com.rabbitmq.client.Delivery)1 ReturnListener (com.rabbitmq.client.ReturnListener)1 ShutdownListener (com.rabbitmq.client.ShutdownListener)1 ShutdownSignalException (com.rabbitmq.client.ShutdownSignalException)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 TimeoutException (java.util.concurrent.TimeoutException)1 ConsumerRecord (org.apache.kafka.clients.consumer.ConsumerRecord)1 WakeupException (org.apache.kafka.common.errors.WakeupException)1