java - 是否可以使用 Kafka 将 Java 对象发送到 C# 应用程序

标签 java c# spring-boot apache-kafka confluent-schema-registry

是否可以将 Java 对象(比如说用户)发送到一个主题,该主题在 C# 中被使用并序列化为用户对象?

假设我有以下从 Java PoJo 构建的 avro 架构(字段是姓名和年龄)

{
  "namespace": "io.confluent.developer",
  "type": "record",
  "name": "User",
  "fields": [
    {
      "name": "name",
      "type": [
        "null",
        "string"
      ],
      "default": null
    },
    {
      "name": "age",
      "type": [
        "null",
        "int"
      ],
      "default": null
    }
  ]
}

生成 User.class

然后像这样发送:

Service
@CommonsLog(topic = "Producer Logger")
@RequiredArgsConstructor
public class Producer {

  @Value("${topic.name}")
  private String TOPIC;

  private final KafkaTemplate<String, User> kafkaTemplate;

  void sendMessage(User user) {
    this.kafkaTemplate.send(this.TOPIC, user.getName(), user);
    log.info(String.format("Produced user -> %s", user));
  }
}

我还有一个架构注册表,但我不知道如何在 C# 中使用消息并将其反序列化为具有相同字段的 User 类:

public class Users

{

    public int id = 0;

    public string name = string.Empty;

    public Users()

    {

        // Constructor Statements

    }

    public void GetUserDetails(int uid, string uname)

    {

        id = uid;

        uname = name;

        Console.WriteLine("Id: {0}, Name: {1}", id, name);

    }

    public int Designation { get; set; }

    public string Location { get; set; }

}

感谢您的帮助。

最佳答案

是的,这是可能的。您可以使用official .NET kafka client消费消息。

您要做的第一件事是根据您使用的相同架构生成 C# 类。您可以通过以下方式做到这一点:

  1. 安装 avrogen 工具: dotnet 工具安装 --global Apache.Avro.Tools
  2. 生成类:avrogen -s user_schema.avsc 。

然后您将获得带有类实现的User.cs。您需要做的就是配置 .NET Kafka 客户端并使用消息:

var schemaRegistryConfig = new SchemaRegistryConfig
{
    Url = "schemaRegistryUrl"
};

var consumerConfig = new ConsumerConfig
{
    BootstrapServers = "bootstrapServers",
    GroupId = "group"
};

using var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig);
using var consumer = new ConsumerBuilder<string, User>(consumerConfig)
    .SetValueDeserializer(new AvroDeserializer<User>(schemaRegistry).AsSyncOverAsync())
    .Build();

consumer.Subscribe(topicName);

var consumeResult = consumer.Consume(cts.Token);

您可以查看this example了解更多信息。

请注意,您不能使用您在问题中提供的 User 类,因为对类结构有一些要求。因此,您应该使用通过 Avro 架构中的工具生成的工具。

关于java - 是否可以使用 Kafka 将 Java 对象发送到 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65847510/

相关文章:

java - Java中Spring-Boot微服务的监控指标计算

java - 如何防止 Controller 方法在 Chrome 浏览器的 Spring Boot 中运行两次?

java - 如何忽略 spring.factories 中定义的 ApplicationListener?

java - 使用 XOM 插入附加父 XML 元素

java - 始终使用相同端口的多个非同时 Java 客户端-服务器连接

c# - 刷新表单后如何保留绘制的形状?

c# - LINQ to Entities 中的 LastIndexOf

c# - 将 JSON 对象发布到 WCF 服务对象始终为 null

java - 将数据保存在 vector 中并在其他函数中重用

java - 使用 super AND 实例变量的构造函数