In microservices using protobuf, the steps to add a new grpc method are usually:
- Define the grpc method and message in the proto file
- Generate the pb.go file based on the proto file
- Implement the rpc method interface on the server side and write business logic code in the grpc method function
- Use a third-party tool or write a client that calls the grpc method to test
In fact, most of the code involved in these four steps can be generated automatically, simplifying to just define grpc methods and messages in the proto file, and then fill in the specific business logic code in the generated template file.
Dependencies
- Prepare proto file user.proto.
- Installation tool sponge.
After installing the tool sponge, execute the command to open the UI interface:
sponge run
Quickly create a microservice project
Prepare a proto file before creating a microservice, Enter the sponge UI interface, click on 【Protobuf】→ 【create microservice project】in the left menu bar, fill in some parameters to generate common microservice project code.
The microservice framework uses grpc, and also includes commonly used service governance function code, build deployment scripts, etc. The database used is chosen by yourself.
Switch to the user directory and run the command:
# Generate code
make proto
# Open the internal/service/user.go code file and fill in the specific logic code according to the generated sample code.
# Compile and start user service
make run
Open user service code with goland IDE, go to internal/service directory, open user_client_test.go
file, you can test grpc method here, similar to testing interface on swagger interface. Fill in parameters before testing and click green button to test.
This is the generic microservice code generated from the above steps https://github.com/zhufuyi/sponge_examples/tree/main/4_micro-grpc-protobuf
You can automatically add CRUD api interfaces
and manually add custom api interfaces
to the generated generic microservice code, see the detailed documentation for developing generic generic microservice https://go-sponge.com/zh-cn/microservice-development-protobuf
Top comments (0)