The Qt GRPC and
Qt Protobuf
modules together allow you to define data and messages in
proto
files, and then use the code generators, which generate code allowing accessors for fields and gRPC services in the Qt framework. Such code allows users to communicate with the server by sending calls or stream messages.
gRPC is a cross-platform high performance Remote Procedure Call (RPC) framework, that generates client/server bindings for a lot of languages. Usually, you use it to connect services in a microservices-style architecture or connecting mobile applications and browsers to backend services. The gRPC clients and servers can run and talk to each other in various environments, and you can write in any of gRPC’s supported languages. For more details see gRPC Introduction
protoc
, the Google protocol buffers compiler, must be installed to generate code from
.proto
specification files. See
Protoc Installation
.
To start working with the Qt GRPC functionality you should define required services and messages in a
.proto
file. See the
helloworld.proto
范例:
// The service definition. service Salutation { // Sends a greeting rpc SendHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
To add a
.proto
file to a Qt-based project and generate the required source code, you should use the
protoc
compiler with the
qtgrpcgen
and
qtprotobufgen
Qt plugins.
This processing of
proto
files into source code can be automated in CMake using the following commands provided by Qt:
As a result, the full example of a CMake project file, that uses Qt GRPC functionality shall be:
cmake_minimum_required(VERSION 3.16...3.22) project(MyProject) find_package(Qt6 REQUIRED COMPONENTS Protobuf Grpc) qt_standard_project_setup() qt_add_protobuf(MyProtoMessageLib PROTO_FILES path/to/helloworld.proto PROTO_INCLUDES path/to/proto/include ) qt_add_grpc(MyGrpcClient CLIENT PROTO_FILES path/to/helloworld.proto PROTO_INCLUDES path/to/proto/include ) qt_add_executable(MyApp main.cpp) target_link_libraries(MyApp PRIVATE MyGrpcClient MyProtoMessageLib Qt6::Protobuf)
The example above calls the
qt_add_grpc()
CMake function to generate a library called
MyGrpcClient
.
注意:
若
.proto
file API contains messages, then the
qt_add_protobuf()
CMake function should be called to generate protobuf message classes for the project.
Finally, the example creates a target for an executable called MyApp which links to the MyGrpcClient and MyProtoMessageLib libraries.
Qt GRPC is available under commercial licenses from Qt 公司 。此外,它是可用的根据 GNU GPL (一般公共许可) 第 3 版 。见 Qt 许可 进一步了解细节。
gRPC ® is a registered trademark of The Linux Foundation. Please see https://grpc.io/ 了解更多信息。