Exemplo n.º 1
0
        public short Produce(string topicName, int partitionId, string data)
        {
            try
            {
                if (!topicPartitionDictionary.ContainsKey(topicName))
                {
                    // Check if topic exist and on what partition.
                    // This call will automatically create the topic if the brooker is set up to auto create
                    MetadataResponse metadataResponse = connector.Metadata(DefaultCorrelationId, clientId, topicName);
                    short            errorCode        = metadataResponse.TopicErrorCode(topicName);
                    if (errorCode != (short)KafkaErrorCode.NoError)
                    {
                        if (errorCode != (short)KafkaErrorCode.LeaderNotAvailable)
                        {
                            return(errorCode);
                        }
                        // Check if the topic was auto created
                        metadataResponse = connector.Metadata(DefaultCorrelationId, clientId, topicName);
                        errorCode        = metadataResponse.TopicErrorCode(topicName);
                        if (errorCode != (short)KafkaErrorCode.NoError)
                        {
                            return(errorCode);
                        }
                        topicPartitionDictionary.Add(topicName, metadataResponse.Partitions(topicName)[0]);
                    }
                    else
                    {
                        topicPartitionDictionary.Add(topicName, metadataResponse.Partitions(topicName)[0]);
                    }
                }

                if (partitionId == -1)
                {
                    partitionId = topicPartitionDictionary[topicName];
                }
                var message = Encoding.UTF8.GetBytes(data);

                ProduceResponse response = connector.Produce(DefaultCorrelationId, clientId, 500, topicName, partitionId, message);
                return(response.ErrorCode(topicName, 0));
            }
            catch (SocketException ex)
            {
                throw new KafkaException(ex.Message);
            }
        }