1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
|
@SuppressWarnings({ "rawtypes", "unchecked" }) @SPI("kafka") public class CanalKafkaProducer extends AbstractMQProducer implements CanalMQProducer {
private static final Logger logger = LoggerFactory.getLogger(CanalKafkaProducer.class);
private static final String PREFIX_KAFKA_CONFIG = "kafka.";
private Producer<String, byte[]> producer;
@Override public void init(Properties properties) { KafkaProducerConfig kafkaProducerConfig = new KafkaProducerConfig(); this.mqProperties = kafkaProducerConfig; super.init(properties); this.loadKafkaProperties(properties);
Properties kafkaProperties = new Properties(); kafkaProperties.putAll(kafkaProducerConfig.getKafkaProperties()); kafkaProperties.put("max.in.flight.requests.per.connection", 1); kafkaProperties.put("key.serializer", StringSerializer.class); if (kafkaProducerConfig.isKerberosEnabled()) { File krb5File = new File(kafkaProducerConfig.getKrb5File()); File jaasFile = new File(kafkaProducerConfig.getJaasFile()); if (krb5File.exists() && jaasFile.exists()) { System.setProperty("java.security.krb5.conf", krb5File.getAbsolutePath()); System.setProperty("java.security.auth.login.config", jaasFile.getAbsolutePath()); System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); kafkaProperties.put("security.protocol", "SASL_PLAINTEXT"); kafkaProperties.put("sasl.kerberos.service.name", "kafka"); } else { String errorMsg = "ERROR # The kafka kerberos configuration file does not exist! please check it"; logger.error(errorMsg); throw new RuntimeException(errorMsg); } } kafkaProperties.put("value.serializer", KafkaMessageSerializer.class); producer = new KafkaProducer<>(kafkaProperties); }
private void loadKafkaProperties(Properties properties) { KafkaProducerConfig kafkaProducerConfig = (KafkaProducerConfig) this.mqProperties; Map<String, Object> kafkaProperties = kafkaProducerConfig.getKafkaProperties(); doMoreCompatibleConvert("canal.mq.servers", "kafka.bootstrap.servers", properties); doMoreCompatibleConvert("canal.mq.acks", "kafka.acks", properties); doMoreCompatibleConvert("canal.mq.compressionType", "kafka.compression.type", properties); doMoreCompatibleConvert("canal.mq.retries", "kafka.retries", properties); doMoreCompatibleConvert("canal.mq.batchSize", "kafka.batch.size", properties); doMoreCompatibleConvert("canal.mq.lingerMs", "kafka.linger.ms", properties); doMoreCompatibleConvert("canal.mq.maxRequestSize", "kafka.max.request.size", properties); doMoreCompatibleConvert("canal.mq.bufferMemory", "kafka.buffer.memory", properties); doMoreCompatibleConvert("canal.mq.kafka.kerberos.enable", "kafka.kerberos.enable", properties); doMoreCompatibleConvert("canal.mq.kafka.kerberos.krb5.file", "kafka.kerberos.krb5.file", properties); doMoreCompatibleConvert("canal.mq.kafka.kerberos.jaas.file", "kafka.kerberos.jaas.file", properties);
for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); Object value = entry.getValue(); if (key.startsWith(PREFIX_KAFKA_CONFIG) && value != null) { value = PropertiesUtils.getProperty(properties, key); key = key.substring(PREFIX_KAFKA_CONFIG.length()); kafkaProperties.put(key, value); } } String kerberosEnabled = PropertiesUtils.getProperty(properties, KafkaConstants.CANAL_MQ_KAFKA_KERBEROS_ENABLE); if (!StringUtils.isEmpty(kerberosEnabled)) { kafkaProducerConfig.setKerberosEnabled(Boolean.parseBoolean(kerberosEnabled)); } String krb5File = PropertiesUtils.getProperty(properties, KafkaConstants.CANAL_MQ_KAFKA_KERBEROS_KRB5_FILE); if (!StringUtils.isEmpty(krb5File)) { kafkaProducerConfig.setKrb5File(krb5File); } String jaasFile = PropertiesUtils.getProperty(properties, KafkaConstants.CANAL_MQ_KAFKA_KERBEROS_JAAS_FILE); if (!StringUtils.isEmpty(jaasFile)) { kafkaProducerConfig.setJaasFile(jaasFile); } }
@Override public void stop() { try { logger.info("## stop the kafka producer"); if (producer != null) { producer.close(); } super.stop(); } catch (Throwable e) { logger.warn("##something goes wrong when stopping kafka producer:", e); } finally { logger.info("## kafka producer is down."); } }
@Override public void send(MQDestination mqDestination, Message message, Callback callback) { ExecutorTemplate template = new ExecutorTemplate(sendExecutor);
try { List result; if (!StringUtils.isEmpty(mqDestination.getDynamicTopic())) { Map<String, Message> messageMap = MQMessageUtils.messageTopics(message, mqDestination.getTopic(), mqDestination.getDynamicTopic());
for (Map.Entry<String, Message> entry : messageMap.entrySet()) { final String topicName = entry.getKey().replace('.', '_'); final Message messageSub = entry.getValue(); template.submit((Callable) () -> { try { return send(mqDestination, topicName, messageSub, mqProperties.isFlatMessage()); } catch (Exception e) { throw new RuntimeException(e); } }); }
result = template.waitForResult(); } else { result = new ArrayList(); List<Future> futures = send(mqDestination, mqDestination.getTopic(), message, mqProperties.isFlatMessage()); result.add(futures); }
producer.flush(); for (Object obj : result) { List<Future> futures = (List<Future>) obj; for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }
callback.commit(); } catch (Throwable e) { logger.error(e.getMessage(), e); callback.rollback(); } finally { template.clear(); } }
private List<Future> send(MQDestination mqDestination, String topicName, Message message, boolean flat) { List<ProducerRecord<String, byte[]>> records = new ArrayList<>(); Integer partitionNum = MQMessageUtils.parseDynamicTopicPartition(topicName, mqDestination.getDynamicTopicPartitionNum()); if (partitionNum == null) { partitionNum = mqDestination.getPartitionsNum(); } if (!flat) { if (mqDestination.getPartitionHash() != null && !mqDestination.getPartitionHash().isEmpty()) { EntryRowData[] datas = MQMessageUtils.buildMessageData(message, buildExecutor); Message[] messages = MQMessageUtils.messagePartition(datas, message.getId(), partitionNum, mqDestination.getPartitionHash(), this.mqProperties.isDatabaseHash()); int length = messages.length; for (int i = 0; i < length; i++) { Message messagePartition = messages[i]; if (messagePartition != null) { records.add(new ProducerRecord<>(topicName, i, null, CanalMessageSerializerUtil.serializer(messagePartition, mqProperties.isFilterTransactionEntry()))); } } } else { final int partition = mqDestination.getPartition() != null ? mqDestination.getPartition() : 0; records.add(new ProducerRecord<>(topicName, partition, null, CanalMessageSerializerUtil.serializer(message, mqProperties.isFilterTransactionEntry()))); } } else { EntryRowData[] datas = MQMessageUtils.buildMessageData(message, buildExecutor); List<FlatMessage> flatMessages = MQMessageUtils.messageConverter(datas, message.getId()); for (FlatMessage flatMessage : flatMessages) { if (mqDestination.getPartitionHash() != null && !mqDestination.getPartitionHash().isEmpty()) { FlatMessage[] partitionFlatMessage = MQMessageUtils.messagePartition(flatMessage, partitionNum, mqDestination.getPartitionHash(), this.mqProperties.isDatabaseHash()); int length = partitionFlatMessage.length; for (int i = 0; i < length; i++) { FlatMessage flatMessagePart = partitionFlatMessage[i]; if (flatMessagePart != null) { records.add(new ProducerRecord<>(topicName, i, null, JSON.toJSONBytes(flatMessagePart, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.LargeObject))); } } } else { final int partition = mqDestination.getPartition() != null ? mqDestination.getPartition() : 0; records.add(new ProducerRecord<>(topicName, partition, null, JSON.toJSONBytes(flatMessage, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.LargeObject))); } } }
return produce(records); }
private List<Future> produce(List<ProducerRecord<String, byte[]>> records) { List<Future> futures = new ArrayList<>(); for (ProducerRecord record : records) { futures.add(producer.send(record)); }
return futures; }
}
|