Protobuf Oneof

More at https://protobuf.dev/reference/java/java-generated/#oneof-fields.

Protobuf Schema

Here you can see that the Measurement has an oneof field:

syntax = "proto3";
import "google/protobuf/timestamp.proto";

option java_multiple_files = true;
option java_package = "kafka.sandbox.proto";

enum SensorStatus {
  UP = 0;
  ERROR = 1;
}

message Sensor {
  string id = 1;
  SensorStatus status = 2;
}

message Environment {
  double temperature = 1;
  double humidity = 2;
}

message Speed {
  int32 wheel_rpm = 1;
  double speed = 2;
}

message Measurement {
  oneof value {
    Environment environment = 1;
    Speed speed = 2;
  }
  google.protobuf.Timestamp created_at = 3;
  Sensor sensor = 4;
}

Setup

Create a topic:

kafka-topics --create --bootstrap-server kafka1:9092 \
             --replication-factor 3 \
             --partitions 3 \
             --topic client.measurements

Produce

gradle kafka-protobuf-oneof-clients:run --args="produce client.measurements 100"

Consume

You can verify which value is inside (speed or environment) with record.value().getValueCase().

gradle kafka-protobuf-oneof-clients:run --args="consume client.measurements"