Defining a blog service and messages
Table of contents
- What you need
- 1. Create a proto file
- 2. Define a blog post
- 3. Add service methods
- 4. Add request types
- 5. Add a response type
- 6. Compile the proto file
- Next step
Let's begin by defining our gRPC blog service in a proto file.
What you need
No preparation is required for this step. Do check that you've prepared the prerequisites.
1. Create a proto file
Create a file, blog.proto
inside the directory, {project_root}/src/main/proto
. This tutorial uses Protocol Buffers version 3.
syntax = "proto3";
package example.armeria.blog.grpc;
option java_package = "example.armeria.blog.grpc";
option java_multiple_files = true;
2. Define a blog post
In the proto file, define the BlogPost
message type with minimal data.
message BlogPost {
int32 id = 1;
string title = 2;
string content = 3;
int64 createdAt = 4;
int64 modifiedAt = 5;
}
3. Add service methods
Add service methods to the blog service. We have two methods for retrieving blog posts; one is for retrieving a single post and another for multiple posts.
import "google/protobuf/empty.proto";
service BlogService {
rpc CreateBlogPost (CreateBlogPostRequest) returns (BlogPost) {}
rpc GetBlogPost (GetBlogPostRequest) returns (BlogPost) {}
rpc ListBlogPosts (ListBlogPostsRequest) returns (ListBlogPostsResponse) {}
rpc UpdateBlogPost (UpdateBlogPostRequest) returns (BlogPost) {}
rpc DeleteBlogPost (DeleteBlogPostRequest) returns (google.protobuf.Empty) {}
}
4. Add request types
Add request types for create, retrieve, update, and delete operations.
message CreateBlogPostRequest {
string title = 1;
string content = 2;
}
message GetBlogPostRequest { // For retrieving a single post
int32 id = 1;
}
message ListBlogPostsRequest { // For retrieving multiple posts
bool descending = 1;
}
message UpdateBlogPostRequest {
int32 id = 1;
string title = 2;
string content = 3;
}
message DeleteBlogPostRequest {
int32 id = 1;
}
5. Add a response type
Add a response type to return multiple blog posts.
message ListBlogPostsResponse {
repeated BlogPost blogs = 1;
}
6. Compile the proto file
Compile the blog.proto
file to generate Java code.
You can refer to the full build.gradle file for generating code with protobuf-gradle-plugin.
./gradlew generateProto
You'll see the generated Java code in the {project_root}/build/generated/source/proto/main
folder.
Next step
In this step, we've defined a proto file for our service and generated Java code. Next, we'll run a service and test the connection.