oneOf lets a Protocol Buffers message carry one member from several alternative fields. It must live inside a message, not stand alone at the top level. section 3.6
For a topic containing related customer events, an outer Events message can select PurchaseEvent, LoginEvent, or SearchEvent while preserving their ordering in one topic. Generated Java code represents the alternatives through the wrapper’s type field. section 3.6 section 4.6.1
Producing and consuming Events
Configure KafkaProtobufSerializer and use Events as the KafkaProducer value type. On consumption, configure KafkaProtobufDeserializer with Events.class, then inspect hasLoginEvent(), hasSearchEvent(), or hasPurchaseEvent(); alternatively, switch on Events.getTypeCase() and process the selected object. section 4.6.1 section 4.6.2
Listing 3.38 Protobuf file with references
syntax = "proto3";
package bbejeck.chapter_3.proto;
import "purchase_event.proto"; #1
import "login_event.proto";
import "search_event.proto";
option java_multiple_files = true;
option java_outer_classname = "EventsProto";
message Events {
oneof type { #2
PurchaseEvent purchase_event = 1;
LoginEvent login_event = 2;
SearchEvent search_event = 3;
}
string key = 4;
}
Review the complete proto3 definition, including imported event schemas, the oneOf alternatives, and the wrapper key. section 3.6
switch (event.getTypeCase()) {
case LOGIN_EVENT -> { #1
logins.add(event.getLoginEvent()); #2
}
case SEARCH_EVENT -> {
searches.add(event.getSearchEvent());
}
case PURCHASE_EVENT -> {
purchases.add(event.getPurchaseEvent());
}
}
Compare enum-based dispatch branches for login, search, and purchase events. section 4.6.2
