From the course: Building Java Microservices with gRPC

Using protocol buffers

From the course: Building Java Microservices with gRPC

Start my 1-month free trial

Using protocol buffers

- [Instructor] Now that we know what protocol buffers are, let us see how to use them. We will begin by writing a text file with a .proto extension. This will signify that it is a protobuffs file, and this file will contain your entire service definition. Let us see, in a gist, how it will look like. This line will specify the name of the service. So EmployeeService is the service class for your file. Inside this, we will define a method called getEmployee. It is an RPC method. The input for this is a message called EmployeeRequest, and this method returns another message called EmployeeResponse. This line denotes the remote service method for your service. In addition to this, you also need to define the EmployeeRequest and EmployeeResponse messages. This is how we do it. The EmployeeResponse message contains four fields: an ID, a username, a name, and a designation. Each of these fields has a number assigned to them. This number is used as a tag to identify the field in the binary message format that gets transported over the HTTP/2 protocol. Similarly, we've also defined EmployeeRequest that contains just a single field called ID. Please note that this is just a gist of what your file will look like. You have loads of other options that you can specify in your protobuffers file. Once you complete your service definition, the next step will be to use the protoc compiler to generate stubs, and these stubs can be generated according to a language. The protoc compiler is going to generate objects for the corresponding message types that you've defined in your service file. These auto-generated classes will implement automatic encoding and parsing of the protocol buffer data in an efficient binary format. These classes will contain getters and setters for each of the fields that you've defined in your message types. These classes will then, in turn, help you to retrieve or set protocol buffered employee messages. We will do a quick demo of this on the Windows operating system in our next video.

Contents