Asp.net core Kafka-在ASP.Net核心中实例化生产者类时出错
我使用的是合流的卡夫卡Asp.net core Kafka-在ASP.Net核心中实例化生产者类时出错,asp.net-core,apache-kafka,kafka-producer-api,apache-kafka-connect,Asp.net Core,Apache Kafka,Kafka Producer Api,Apache Kafka Connect,我使用的是合流的卡夫卡 string kafkaEndpoint = "127.0.0.1:9092"; string kafkaTopic = "testtopic"; var producerConfig = new Dictionary<string, object> { { "bootstrap.servers", kafkaEndpoint } }; using (var producer = new Producer&
string kafkaEndpoint = "127.0.0.1:9092";
string kafkaTopic = "testtopic";
var producerConfig = new Dictionary<string, object> { { "bootstrap.servers", kafkaEndpoint } };
using (var producer = new Producer<Null, string>(producerConfig, null, new StringSerializer(Encoding.UTF8)))
{
// Send 10 messages to the topic
for (int i = 0; i < 10; i++)
{
var message = $"Event {i}";
var result = producer.ProduceAsync(kafkaTopic, null, message).GetAwaiter().GetResult();
Console.WriteLine($"Event {i} sent on Partition: {result.Partition} with Offset: {result.Offset}");
}
}
显示错误:
Cannot convert from 'Confluent.Kafka.Message<Confluent.Kafka.Null, MyClass>' to 'Confluent.Kafka.Message<Confluent.Kafka.Null, string>
无法从“Confluent.Kafka.Message”转换为“Confluent.Kafka.Message”
在Confluent.Kafka
nuget v1.0.1中,Producer
类是一个内部类,即它是不可访问的。看起来您需要改用ProducerBuilder
,例如:
var producerConfig = new Dictionary<string, string> { { "bootstrap.servers", kafkaEndpoint } };
using (var producer = new ProducerBuilder<Null, string>(producerConfig)
.SetKeySerializer(Serializers.Null)
.SetValueSerializer(Serializers.Utf8)
.Build())
{
// Send 10 messages to the topic
for (int i = 0; i < 10; i++)
{
var message = $"Event {i}";
var result = producer.ProduceAsync(kafkaTopic, new Message<Null, string>{ Value = message}).GetAwaiter().GetResult();
Console.WriteLine($"Event {i} sent on Partition: {result.Partition} with Offset: {result.Offset}");
}
}
对我注意到这个班在内部。我是否需要使用其他软件包来使用它,因为在我遵循的所有文档中,他们使用的是Producer类看起来不需要额外的NUGET,只需要
Confluent.Kafka
。我已经更新了我的答案,ProducerBuilder要求producerConfig
成为Dictionary
谢谢@Renat。我试图使用Producer
类,因为我想发送类的实例,而不是消息,如何使用ProducerBuilder
传递对象?我第一次尝试卡夫卡,我没有idea@AdritaSharma,看起来将消息类型从string
更改为自定义类型会起作用:producer.ProduceAsync(kafkaTopic,新消息{Value=myObject})..
var producerConfig = new Dictionary<string, string> { { "bootstrap.servers", kafkaEndpoint } };
using (var producer = new ProducerBuilder<Null, string>(producerConfig)
.SetKeySerializer(Serializers.Null)
.SetValueSerializer(Serializers.Utf8)
.Build())
{
// Send 10 messages to the topic
for (int i = 0; i < 10; i++)
{
var message = $"Event {i}";
var result = producer.ProduceAsync(kafkaTopic, new Message<Null, string>{ Value = message}).GetAwaiter().GetResult();
Console.WriteLine($"Event {i} sent on Partition: {result.Partition} with Offset: {result.Offset}");
}
}
var result = producer.ProduceAsync(kafkaTopic, new Message<Null, MyClass>{ Value = myObject}).GetAwaiter().GetResult();