快速入门
本指南通过一个简单的示例,帮助您开始使用 PHP 中的 gRPC。
快速入门
先决条件
- PHP 7.0 或更高版本,PECL,Composer
- grpc 扩展,协议缓冲区编译器:有关安装说明,请参阅 gRPC PHP readme。
获取示例代码
示例代码是 grpc 仓库的一部分。
注意
您只能在 PHP 中创建 gRPC 客户端。请使用 其他语言 来创建 gRPC 服务器。克隆 grpc 仓库及其子模块
git clone --recurse-submodules -b v1.71.0 --depth 1 --shallow-submodules https://github.com/grpc/grpc
切换到快速入门示例目录
cd grpc/examples/php
安装
grpc
composer 包./greeter_proto_gen.sh composer install
运行示例
启动快速入门服务器:例如,遵循 Node 快速入门 中的说明。
从
examples/php
目录运行 PHP 客户端./run_greeter_client.sh
恭喜!您已成功运行一个使用 gRPC 的客户端-服务器应用程序。
更新 gRPC 服务
现在,让我们看看如何通过在服务器上添加一个客户端可以调用的额外方法来更新应用程序。我们的 gRPC 服务是使用 protocol buffers 定义的;您可以在 基础教程 中找到更多关于如何在 .proto
文件中定义服务的信息。目前,您只需要知道服务器和客户端“桩”(stub)都包含一个 SayHello
RPC 方法,该方法接受客户端的 HelloRequest
参数,并从服务器返回一个 HelloResponse
,并且此方法定义如下
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (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;
}
让我们更新此定义,以便 Greeter
服务有两个方法。编辑 examples/protos/helloworld.proto
,并添加一个新的 SayHelloAgain
方法,使用相同的请求和响应类型
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (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;
}
记住保存文件!
重新生成 gRPC 代码
接下来,我们需要更新应用程序使用的 gRPC 代码,以使用新的服务定义。从 grpc
根目录执行:
protoc --proto_path=examples/protos \
--php_out=examples/php \
--grpc_out=examples/php \
--plugin=protoc-gen-grpc=bins/opt/grpc_php_plugin \
./examples/protos/helloworld.proto
或者如果您从源代码构建了 grpc-php-plugin,可以运行 grpc/example/php
目录下的辅助脚本:
./greeter_proto_gen.sh
这将重新生成 protobuf 文件,其中包含我们生成的客户端类,以及用于填充、序列化和检索请求及响应类型的类。
更新并运行应用程序
现在我们有了新的生成的客户端代码,但我们仍然需要在示例应用程序的手写部分实现并调用新方法。
更新服务器
在同一目录中,打开 greeter_server.js
。像这样实现新方法:
function sayHello(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}
function sayHelloAgain(call, callback) {
callback(null, {message: 'Hello again, ' + call.request.name});
}
function main() {
var server = new grpc.Server();
server.addProtoService(hello_proto.Greeter.service,
{sayHello: sayHello, sayHelloAgain: sayHelloAgain});
server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
server.start();
}
...
更新客户端
在同一目录中,打开 greeter_client.php
。像这样调用新方法:
$request = new Helloworld\HelloRequest();
$request->setName($name);
list($reply, $status) = $client->SayHello($request)->wait();
$message = $reply->getMessage();
list($reply, $status) = $client->SayHelloAgain($request)->wait();
$message = $reply->getMessage();
运行!
就像之前一样,从 grpc-node/examples/helloworld/dynamic_codegen
目录执行:
运行服务器
node greeter_server.js
在另一个终端中,从
examples/php
目录运行客户端:./run_greeter_client.sh