Search in sources :

Example 1 with MQDestination

use of com.alibaba.otter.canal.connector.core.producer.MQDestination in project canal by alibaba.

the class CanalRocketMQProducer method send.

public void send(final MQDestination destination, String topicName, com.alibaba.otter.canal.protocol.Message message) {
    // 获取当前topic的分区数
    Integer partitionNum = MQMessageUtils.parseDynamicTopicPartition(topicName, destination.getDynamicTopicPartitionNum());
    // 获取topic的队列数为分区数
    if (partitionNum == null) {
        partitionNum = getTopicDynamicQueuesSize(destination.getEnableDynamicQueuePartition(), topicName);
    }
    if (partitionNum == null) {
        partitionNum = destination.getPartitionsNum();
    }
    if (!mqProperties.isFlatMessage()) {
        if (destination.getPartitionHash() != null && !destination.getPartitionHash().isEmpty()) {
            // 并发构造
            MQMessageUtils.EntryRowData[] datas = MQMessageUtils.buildMessageData(message, buildExecutor);
            // 串行分区
            com.alibaba.otter.canal.protocol.Message[] messages = MQMessageUtils.messagePartition(datas, message.getId(), partitionNum, destination.getPartitionHash(), mqProperties.isDatabaseHash());
            int length = messages.length;
            ExecutorTemplate template = new ExecutorTemplate(sendPartitionExecutor);
            for (int i = 0; i < length; i++) {
                com.alibaba.otter.canal.protocol.Message dataPartition = messages[i];
                if (dataPartition != null) {
                    final int index = i;
                    template.submit(() -> {
                        Message data = new Message(topicName, ((RocketMQProducerConfig) this.mqProperties).getTag(), CanalMessageSerializerUtil.serializer(dataPartition, mqProperties.isFilterTransactionEntry()));
                        sendMessage(data, index);
                    });
                }
            }
            // 等所有分片发送完毕
            template.waitForResult();
        } else {
            final int partition = destination.getPartition() != null ? destination.getPartition() : 0;
            Message data = new Message(topicName, ((RocketMQProducerConfig) this.mqProperties).getTag(), CanalMessageSerializerUtil.serializer(message, mqProperties.isFilterTransactionEntry()));
            sendMessage(data, partition);
        }
    } else {
        // 并发构造
        MQMessageUtils.EntryRowData[] datas = MQMessageUtils.buildMessageData(message, buildExecutor);
        // 串行分区
        List<FlatMessage> flatMessages = MQMessageUtils.messageConverter(datas, message.getId());
        // 初始化分区合并队列
        if (destination.getPartitionHash() != null && !destination.getPartitionHash().isEmpty()) {
            List<List<FlatMessage>> partitionFlatMessages = new ArrayList<>();
            for (int i = 0; i < partitionNum; i++) {
                partitionFlatMessages.add(new ArrayList<>());
            }
            for (FlatMessage flatMessage : flatMessages) {
                FlatMessage[] partitionFlatMessage = MQMessageUtils.messagePartition(flatMessage, partitionNum, destination.getPartitionHash(), mqProperties.isDatabaseHash());
                int length = partitionFlatMessage.length;
                for (int i = 0; i < length; i++) {
                    // 增加null判断,issue #3267
                    if (partitionFlatMessage[i] != null) {
                        partitionFlatMessages.get(i).add(partitionFlatMessage[i]);
                    }
                }
            }
            ExecutorTemplate template = new ExecutorTemplate(sendPartitionExecutor);
            for (int i = 0; i < partitionFlatMessages.size(); i++) {
                final List<FlatMessage> flatMessagePart = partitionFlatMessages.get(i);
                if (flatMessagePart != null && flatMessagePart.size() > 0) {
                    final int index = i;
                    template.submit(() -> {
                        List<Message> messages = flatMessagePart.stream().map(flatMessage -> new Message(topicName, ((RocketMQProducerConfig) this.mqProperties).getTag(), JSON.toJSONBytes(flatMessage, SerializerFeature.WriteMapNullValue))).collect(Collectors.toList());
                        // 批量发送
                        sendMessage(messages, index);
                    });
                }
            }
            // 批量等所有分区的结果
            template.waitForResult();
        } else {
            final int partition = destination.getPartition() != null ? destination.getPartition() : 0;
            List<Message> messages = flatMessages.stream().map(flatMessage -> new Message(topicName, ((RocketMQProducerConfig) this.mqProperties).getTag(), JSON.toJSONBytes(flatMessage, SerializerFeature.WriteMapNullValue))).collect(Collectors.toList());
            // 批量发送
            sendMessage(messages, partition);
        }
    }
}
Also used : Callback(com.alibaba.otter.canal.connector.core.util.Callback) StringUtils(org.apache.commons.lang.StringUtils) Message(org.apache.rocketmq.common.message.Message) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SerializerFeature(com.alibaba.fastjson.serializer.SerializerFeature) RPCHook(org.apache.rocketmq.remoting.RPCHook) AclClientRPCHook(org.apache.rocketmq.acl.common.AclClientRPCHook) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) LoggerFactory(org.slf4j.LoggerFactory) CanalMessageSerializerUtil(com.alibaba.otter.canal.connector.core.util.CanalMessageSerializerUtil) PropertiesUtils(com.alibaba.otter.canal.common.utils.PropertiesUtils) ArrayList(java.util.ArrayList) RocketMQConstants(com.alibaba.otter.canal.connector.rocketmq.config.RocketMQConstants) MQClientException(org.apache.rocketmq.client.exception.MQClientException) MQMessageUtils(com.alibaba.otter.canal.connector.core.producer.MQMessageUtils) FlatMessage(com.alibaba.otter.canal.protocol.FlatMessage) Map(java.util.Map) DefaultMQProducerImpl(org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl) SendResult(org.apache.rocketmq.client.producer.SendResult) ExecutorTemplate(com.alibaba.otter.canal.common.utils.ExecutorTemplate) DefaultMQProducer(org.apache.rocketmq.client.producer.DefaultMQProducer) RocketMQProducerConfig(com.alibaba.otter.canal.connector.rocketmq.config.RocketMQProducerConfig) MQDestination(com.alibaba.otter.canal.connector.core.producer.MQDestination) Logger(org.slf4j.Logger) Properties(java.util.Properties) NamedThreadFactory(com.alibaba.otter.canal.common.utils.NamedThreadFactory) SPI(com.alibaba.otter.canal.connector.core.spi.SPI) Collectors(java.util.stream.Collectors) CanalException(com.alibaba.otter.canal.common.CanalException) TimeUnit(java.util.concurrent.TimeUnit) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) List(java.util.List) JSON(com.alibaba.fastjson.JSON) SessionCredentials(org.apache.rocketmq.acl.common.SessionCredentials) CanalMQProducer(com.alibaba.otter.canal.connector.core.spi.CanalMQProducer) TopicPublishInfo(org.apache.rocketmq.client.impl.producer.TopicPublishInfo) AbstractMQProducer(com.alibaba.otter.canal.connector.core.producer.AbstractMQProducer) AccessChannel(org.apache.rocketmq.client.AccessChannel) ExecutorTemplate(com.alibaba.otter.canal.common.utils.ExecutorTemplate) Message(org.apache.rocketmq.common.message.Message) FlatMessage(com.alibaba.otter.canal.protocol.FlatMessage) ArrayList(java.util.ArrayList) FlatMessage(com.alibaba.otter.canal.protocol.FlatMessage) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with MQDestination

use of com.alibaba.otter.canal.connector.core.producer.MQDestination in project canal by alibaba.

the class CanalMQStarter method worker.

private void worker(String destination, AtomicBoolean destinationRunning) {
    while (!running || !destinationRunning.get()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        // ignore
        }
    }
    logger.info("## start the MQ producer: {}.", destination);
    MDC.put("destination", destination);
    final ClientIdentity clientIdentity = new ClientIdentity(destination, (short) 1001, "");
    while (running && destinationRunning.get()) {
        try {
            CanalInstance canalInstance = canalServer.getCanalInstances().get(destination);
            if (canalInstance == null) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                // ignore
                }
                continue;
            }
            MQDestination canalDestination = new MQDestination();
            canalDestination.setCanalDestination(destination);
            CanalMQConfig mqConfig = canalInstance.getMqConfig();
            canalDestination.setTopic(mqConfig.getTopic());
            canalDestination.setPartition(mqConfig.getPartition());
            canalDestination.setDynamicTopic(mqConfig.getDynamicTopic());
            canalDestination.setPartitionsNum(mqConfig.getPartitionsNum());
            canalDestination.setPartitionHash(mqConfig.getPartitionHash());
            canalDestination.setDynamicTopicPartitionNum(mqConfig.getDynamicTopicPartitionNum());
            canalDestination.setEnableDynamicQueuePartition(mqConfig.getEnableDynamicQueuePartition());
            canalServer.subscribe(clientIdentity);
            logger.info("## the MQ producer: {} is running now ......", destination);
            Integer getTimeout = mqProperties.getFetchTimeout();
            Integer getBatchSize = mqProperties.getBatchSize();
            while (running && destinationRunning.get()) {
                Message message;
                if (getTimeout != null && getTimeout > 0) {
                    message = canalServer.getWithoutAck(clientIdentity, getBatchSize, getTimeout.longValue(), TimeUnit.MILLISECONDS);
                } else {
                    message = canalServer.getWithoutAck(clientIdentity, getBatchSize);
                }
                final long batchId = message.getId();
                try {
                    int size = message.isRaw() ? message.getRawEntries().size() : message.getEntries().size();
                    if (batchId != -1 && size != 0) {
                        canalMQProducer.send(canalDestination, message, new Callback() {

                            @Override
                            public void commit() {
                                // 提交确认
                                canalServer.ack(clientIdentity, batchId);
                            }

                            @Override
                            public void rollback() {
                                canalServer.rollback(clientIdentity, batchId);
                            }
                        });
                    // 发送message到topic
                    } else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                        // ignore
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            logger.error("process error!", e);
        }
    }
}
Also used : CanalInstance(com.alibaba.otter.canal.instance.core.CanalInstance) Callback(com.alibaba.otter.canal.connector.core.util.Callback) ClientIdentity(com.alibaba.otter.canal.protocol.ClientIdentity) MQDestination(com.alibaba.otter.canal.connector.core.producer.MQDestination) Message(com.alibaba.otter.canal.protocol.Message) CanalMQConfig(com.alibaba.otter.canal.instance.core.CanalMQConfig)

Aggregations

MQDestination (com.alibaba.otter.canal.connector.core.producer.MQDestination)2 Callback (com.alibaba.otter.canal.connector.core.util.Callback)2 JSON (com.alibaba.fastjson.JSON)1 SerializerFeature (com.alibaba.fastjson.serializer.SerializerFeature)1 CanalException (com.alibaba.otter.canal.common.CanalException)1 ExecutorTemplate (com.alibaba.otter.canal.common.utils.ExecutorTemplate)1 NamedThreadFactory (com.alibaba.otter.canal.common.utils.NamedThreadFactory)1 PropertiesUtils (com.alibaba.otter.canal.common.utils.PropertiesUtils)1 AbstractMQProducer (com.alibaba.otter.canal.connector.core.producer.AbstractMQProducer)1 MQMessageUtils (com.alibaba.otter.canal.connector.core.producer.MQMessageUtils)1 CanalMQProducer (com.alibaba.otter.canal.connector.core.spi.CanalMQProducer)1 SPI (com.alibaba.otter.canal.connector.core.spi.SPI)1 CanalMessageSerializerUtil (com.alibaba.otter.canal.connector.core.util.CanalMessageSerializerUtil)1 RocketMQConstants (com.alibaba.otter.canal.connector.rocketmq.config.RocketMQConstants)1 RocketMQProducerConfig (com.alibaba.otter.canal.connector.rocketmq.config.RocketMQProducerConfig)1 CanalInstance (com.alibaba.otter.canal.instance.core.CanalInstance)1 CanalMQConfig (com.alibaba.otter.canal.instance.core.CanalMQConfig)1 ClientIdentity (com.alibaba.otter.canal.protocol.ClientIdentity)1 FlatMessage (com.alibaba.otter.canal.protocol.FlatMessage)1 Message (com.alibaba.otter.canal.protocol.Message)1