gpt4 book ai didi

asp.net-core - Kafka - 在 ASP.Net Core 中实例化生产者类时出错

转载 作者:行者123 更新时间:2023-12-02 02:38:15 25 4
gpt4 key购买 nike

我正在使用Confluence.Kafka

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}");
}
}

我收到以下编译时错误:

Producer.ProduceAsync(TopicPartition, Message)' is inaccessible due to its protection level

像这样使用ProducerBuilder:

var result = producer.ProduceAsync(kafkaTopic, new Message<Null, MyClass>{ Value = myObject}).GetAwaiter().GetResult();

显示错误:

Cannot convert from 'Confluent.Kafka.Message<Confluent.Kafka.Null, MyClass>' to 'Confluent.Kafka.Message<Confluent.Kafka.Null, string>

最佳答案

Confluence.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}");
}
}

看起来可以将任意类的实例发送为(用目标类替换 MyClass):

        var result = producer.ProduceAsync(kafkaTopic, new Message<Null, MyClass>{ Value = myObject}).GetAwaiter().GetResult();

关于asp.net-core - Kafka - 在 ASP.Net Core 中实例化生产者类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com