Search in sources :

Example 51 with Callback

use of org.apache.kafka.clients.producer.Callback in project registry by hortonworks.

the class KafkaAvroSerDesApp method sendMessages.

public void sendMessages(String payloadJsonFile) throws Exception {
    Properties props = new Properties();
    try (FileInputStream fileInputStream = new FileInputStream(this.producerProps)) {
        props.load(fileInputStream);
    }
    int limit = Integer.parseInt(props.getProperty(MSGS_LIMIT_OLD, props.getProperty(MSGS_LIMIT, DEFAULT_MSGS_LIMIT + "")));
    boolean ignoreInvalidMsgs = Boolean.parseBoolean(props.getProperty(IGNORE_INVALID_MSGS, "false"));
    int current = 0;
    Schema schema = new Schema.Parser().parse(new File(this.schemaFile));
    String topicName = props.getProperty(TOPIC);
    // set protocol version to the earlier one.
    props.put(SERDES_PROTOCOL_VERSION, METADATA_ID_VERSION_PROTOCOL);
    final Producer<String, Object> producer = new KafkaProducer<>(props);
    final Callback callback = new MyProducerCallback();
    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(payloadJsonFile))) {
        String line;
        while (current++ < limit && (line = bufferedReader.readLine()) != null) {
            // convert json to avro records
            Object avroMsg = null;
            try {
                avroMsg = jsonToAvro(line, schema);
            } catch (Exception ex) {
                LOG.warn("Error encountered while converting json to avro of message [{}]", line, ex);
                if (ignoreInvalidMsgs) {
                    continue;
                } else {
                    throw ex;
                }
            }
            // send avro messages to given topic using KafkaAvroSerializer which registers payload schema if it does not exist
            // with schema name as "<topic-name>:v", type as "avro" and schemaGroup as "kafka".
            // schema registry should be running so that KafkaAvroSerializer can register the schema.
            LOG.info("Sending message: [{}] to topic: [{}]", avroMsg, topicName);
            ProducerRecord<String, Object> producerRecord = new ProducerRecord<>(topicName, avroMsg);
            try {
                producer.send(producerRecord, callback);
            } catch (SerDesException ex) {
                LOG.warn("Error encountered while sending message [{}]", line, ex);
                if (!ignoreInvalidMsgs) {
                    throw ex;
                }
            }
        }
    } finally {
        producer.flush();
        LOG.info("All message are successfully sent to topic: [{}]", topicName);
        producer.close(5, TimeUnit.SECONDS);
    }
}
Also used : KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) Schema(org.apache.avro.Schema) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) SerDesException(com.hortonworks.registries.schemaregistry.serde.SerDesException) ParseException(org.apache.commons.cli.ParseException) Callback(org.apache.kafka.clients.producer.Callback) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) SerDesException(com.hortonworks.registries.schemaregistry.serde.SerDesException) File(java.io.File)

Example 52 with Callback

use of org.apache.kafka.clients.producer.Callback in project registry by hortonworks.

the class KafkaAvroSerDesWithKafkaServerTest method produceMessage.

private String produceMessage(String topicName, Object msg) {
    String bootstrapServers = CLUSTER.bootstrapServers();
    Map<String, Object> config = new HashMap<>();
    config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    config.putAll(SCHEMA_REGISTRY_TEST_SERVER_CLIENT_WRAPPER.exportClientConf(true));
    config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
    config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
    final Producer<String, Object> producer = new KafkaProducer<>(config);
    final Callback callback = new ProducerCallback();
    LOG.info("Sending message: [{}] to topic: [{}]", msg, topicName);
    ProducerRecord<String, Object> producerRecord = new ProducerRecord<>(topicName, getKey(msg), msg);
    producer.send(producerRecord, callback);
    producer.flush();
    LOG.info("Message successfully sent to topic: [{}]", topicName);
    producer.close(5, TimeUnit.SECONDS);
    return bootstrapServers;
}
Also used : KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) Callback(org.apache.kafka.clients.producer.Callback) HashMap(java.util.HashMap) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) KafkaAvroSerializer(com.hortonworks.registries.schemaregistry.serdes.avro.kafka.KafkaAvroSerializer)

Example 53 with Callback

use of org.apache.kafka.clients.producer.Callback in project luntan by caoawei.

the class KafkaPublisher method publish.

public static void publish(TopicType topicType, Object message) {
    if (topicType == null) {
        throw new NullPointerException("the topicType can not be null");
    }
    if (message == null) {
        throw new NullPointerException("the message can not be null");
    }
    if (!isEnableKafka()) {
        logger.error("[kafka 当前系统未启用]");
        return;
    }
    if (kafkaProducer == null) {
        synchronized (logger) {
            if (kafkaProducer == null) {
                kafkaProducer = new KafkaProducer<>(KafkaConfig.producerConfig());
            }
        }
    }
    try {
        // 当前系统环境(考虑到实际多套环境版本不尽相同)
        String env = ConfigUtil.getConfig("mq.kafka.env", "");
        String topic = env + "-" + topicType.getTopic();
        String data = Utils.toJson(message);
        ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>(topic, data.getBytes("utf-8"));
        logger.info("[kafka 开始发布消息.....]");
        Future<RecordMetadata> future = kafkaProducer.send(record, new Callback() {

            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception != null) {
                    logger.error("[kafak 发布消息失败] cause:{}", exception.getMessage(), exception);
                    return;
                }
                logger.info("[kafka 发布成功]: 主题:{},分区:{},偏移:{}", metadata.topic(), metadata.partition(), metadata.offset());
            }
        });
    } catch (Exception e) {
        logger.error("[kafka 发布失败]: cause:{}", e.getMessage(), e);
        kafkaProducer.close();
        synchronized (logger) {
            kafkaProducer = null;
        }
    }
}
Also used : RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) Callback(org.apache.kafka.clients.producer.Callback) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord)

Example 54 with Callback

use of org.apache.kafka.clients.producer.Callback in project cruise-control by linkedin.

the class CruiseControlMetricsReporterTest method setUp.

@Before
public void setUp() {
    super.setUp();
    Properties props = new Properties();
    props.setProperty(ProducerConfig.ACKS_CONFIG, "-1");
    AtomicInteger failed = new AtomicInteger(0);
    try (Producer<String, String> producer = createProducer(props)) {
        for (int i = 0; i < 10; i++) {
            producer.send(new ProducerRecord<>("TestTopic", Integer.toString(i)), new Callback() {

                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e != null) {
                        failed.incrementAndGet();
                    }
                }
            });
        }
    }
    assertEquals(0, failed.get());
}
Also used : RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) Callback(org.apache.kafka.clients.producer.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Properties(java.util.Properties) IOException(java.io.IOException) Before(org.junit.Before)

Example 55 with Callback

use of org.apache.kafka.clients.producer.Callback in project nakadi by zalando.

the class KafkaTopicRepositoryTest method whenKafkaPublishTimeoutThenCircuitIsOpened.

@Test
public void whenKafkaPublishTimeoutThenCircuitIsOpened() throws Exception {
    when(nakadiSettings.getKafkaSendTimeoutMs()).thenReturn(1000L);
    when(kafkaProducer.partitionsFor(EXPECTED_PRODUCER_RECORD.topic())).thenReturn(ImmutableList.of(new PartitionInfo(EXPECTED_PRODUCER_RECORD.topic(), 1, new Node(1, "host", 9091), null, null)));
    when(kafkaProducer.send(any(), any())).thenAnswer(invocation -> {
        final Callback callback = (Callback) invocation.getArguments()[1];
        callback.onCompletion(null, new TimeoutException());
        return null;
    });
    final List<BatchItem> batches = new LinkedList<>();
    for (int i = 0; i < 1000; i++) {
        try {
            final BatchItem batchItem = new BatchItem("{}", BatchItem.EmptyInjectionConfiguration.build(1, true), new BatchItem.InjectionConfiguration[BatchItem.Injection.values().length], Collections.emptyList());
            batchItem.setPartition("1");
            batches.add(batchItem);
            kafkaTopicRepository.syncPostBatch(EXPECTED_PRODUCER_RECORD.topic(), ImmutableList.of(batchItem));
            fail();
        } catch (final EventPublishingException e) {
        }
    }
    Assert.assertTrue(batches.stream().filter(item -> item.getResponse().getPublishingStatus() == EventPublishingStatus.FAILED && item.getResponse().getDetail().equals("short circuited")).count() >= 1);
}
Also used : EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) GetChildrenBuilder(org.apache.curator.framework.api.GetChildrenBuilder) KafkaException(org.apache.kafka.common.KafkaException) NakadiException(org.zalando.nakadi.exceptions.NakadiException) Assert.assertThat(org.junit.Assert.assertThat) Future(java.util.concurrent.Future) Arrays.asList(java.util.Arrays.asList) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) Assert.fail(org.junit.Assert.fail) Matchers.anyVararg(org.mockito.Matchers.anyVararg) Consumer(org.apache.kafka.clients.consumer.Consumer) ZooKeeperHolder(org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder) PartitionStatistics(org.zalando.nakadi.domain.PartitionStatistics) Set(java.util.Set) PartitionInfo(org.apache.kafka.common.PartitionInfo) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) Collectors(java.util.stream.Collectors) Matchers.any(org.mockito.Matchers.any) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) TestUtils.buildTimelineWithTopic(org.zalando.nakadi.utils.TestUtils.buildTimelineWithTopic) Timeline(org.zalando.nakadi.domain.Timeline) ZookeeperSettings(org.zalando.nakadi.repository.zookeeper.ZookeeperSettings) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) BatchItem(org.zalando.nakadi.domain.BatchItem) Node(org.apache.kafka.common.Node) Matchers.is(org.hamcrest.Matchers.is) Callback(org.apache.kafka.clients.producer.Callback) Mockito.mock(org.mockito.Mockito.mock) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) NakadiSettings(org.zalando.nakadi.config.NakadiSettings) Cursor(org.zalando.nakadi.view.Cursor) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) UUIDGenerator(org.zalando.nakadi.util.UUIDGenerator) HashSet(java.util.HashSet) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) TimeoutException(org.apache.kafka.common.errors.TimeoutException) PartitionEndStatistics(org.zalando.nakadi.domain.PartitionEndStatistics) Test(org.junit.Test) BufferExhaustedException(org.apache.kafka.clients.producer.BufferExhaustedException) Mockito.when(org.mockito.Mockito.when) Mockito(org.mockito.Mockito) Collectors.toList(java.util.stream.Collectors.toList) EventPublishingStatus(org.zalando.nakadi.domain.EventPublishingStatus) CursorError(org.zalando.nakadi.domain.CursorError) Assert(org.junit.Assert) Collections(java.util.Collections) Callback(org.apache.kafka.clients.producer.Callback) Node(org.apache.kafka.common.Node) BatchItem(org.zalando.nakadi.domain.BatchItem) PartitionInfo(org.apache.kafka.common.PartitionInfo) EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) LinkedList(java.util.LinkedList) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Test(org.junit.Test)

Aggregations

Callback (org.apache.kafka.clients.producer.Callback)81 Test (org.junit.Test)47 ProducerRecord (org.apache.kafka.clients.producer.ProducerRecord)39 RecordMetadata (org.apache.kafka.clients.producer.RecordMetadata)37 KafkaException (org.apache.kafka.common.KafkaException)21 Future (java.util.concurrent.Future)18 TimeoutException (org.apache.kafka.common.errors.TimeoutException)18 ExecutionException (java.util.concurrent.ExecutionException)15 ArrayList (java.util.ArrayList)14 List (java.util.List)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)13 MockProducer (org.apache.kafka.clients.producer.MockProducer)13 HashMap (java.util.HashMap)12 Properties (java.util.Properties)12 DefaultPartitioner (org.apache.kafka.clients.producer.internals.DefaultPartitioner)12 TopicPartition (org.apache.kafka.common.TopicPartition)12 Schema (org.apache.kafka.connect.data.Schema)12 Struct (org.apache.kafka.connect.data.Struct)12 KafkaProducer (org.apache.kafka.clients.producer.KafkaProducer)11 StreamsException (org.apache.kafka.streams.errors.StreamsException)11