Comprehensive Guide to gRPC Communication with Go and PHP: Protobuf, Streaming, TLS, and Timeout
This comprehensive guide walks you through creating a gRPC user service in Go and PHP, from defining protobuf messages and generating code, implementing server and client stubs, adding client, server, and bidirectional streaming, securing communication with TLS certificates, and managing request deadlines with timeout controls.
This article provides a step‑by‑step tutorial on building gRPC services using Go and PHP. It starts with an introduction to gRPC and the need to understand protobuf syntax and the protoc compiler.
1. Requirement Analysis – a simple user service with two RPC methods: SaveUser and GetUserInfo . Example pseudo‑code is shown:
function1 saveUser(name, age) return (UID)
function1 getUserInfo(UID) return (UID, name, age)2. Protobuf Definition – the .proto file defines messages Id , Name , Age , UserInfo , UserParams and the service UserServer with the two RPC methods.
service UserServer {
rpc SaveUser (UserParams) returns (Id) {}
rpc GetUserInfo (Id) returns (UserInfo) {}
}3. Generating Go Code – compile the protobuf file with:
protoc --go_out=plugins=grpc:. userServer.protoThe generated userServer.pb.go contains Go structs and client/server stubs.
4. Implementing the Go Server – create a TCP listener, register the service, and implement the two methods. Example:
func (s *UserServer) SaveUser(ctx context.Context, p *proto.UserParams) (*proto.Id, error) {
id := rand.Int31n(100)
fmt.Printf("%+v %s\n", p.GetAge(), p.GetName())
return &proto.Id{Id: id}, nil
}
func (s *UserServer) GetUserInfo(ctx context.Context, id *proto.Id) (*proto.UserInfo, error) {
return &proto.UserInfo{Id: id.GetId(), Name: "test", Age: 31}, nil
}5. Go Client – connect with grpc.Dial , create a client stub, and call the RPCs:
conn, _ := grpc.Dial("127.0.0.1:9527", grpc.WithInsecure())
client := proto.NewUserServerClient(conn)
res, _ := client.SaveUser(context.Background(), ¶ms)
info, _ := client.GetUserInfo(context.Background(), &proto.Id{Id: 1})The article shows the expected console output for both server and client.
6. PHP Client – after generating PHP classes with protoc and the grpc_php_plugin , the PHP client uses Composer autoloading and calls the same RPCs:
require __DIR__.'/vendor/autoload.php';
$client = new \Proto\UserServerClient('127.0.0.1:9527', ['credentials'=>Grpc\ChannelCredentials::createInsecure()]);
$params = new \Proto\UserParams();
$params->setAge((new \Proto\Age())->setAge('18'));
$params->setName((new \Proto\Name())->setName('jack'));
list($id, $status) = $client->SaveUser($params)->wait();
list($info, $status) = $client->GetUserInfo((new \Proto\Id())->setId('1'))->wait();Outputs are displayed with var_dump .
7. Streaming RPCs – the guide extends the service with client‑side, server‑side, and bidirectional streaming methods ( SaveArticle , GetArticleInfo , DeleteArticle ). It provides full protobuf definitions, Go server implementations using loops with stream.Recv() and stream.Send() , and matching Go and PHP client code that demonstrates sending multiple messages in a stream and handling responses.
8. TLS Encryption – explains the HTTPS/TLS handshake and shows how to generate a self‑signed certificate with OpenSSL. Go server uses credentials.NewServerTLSFromFile and the client uses credentials.NewClientTLSFromFile together with grpc.WithTransportCredentials . PHP client loads the PEM file via Grpc\ChannelCredentials::createSsl and sets grpc.ssl_target_name_override to match the certificate’s DNS name.
9. Timeout Control – demonstrates setting a deadline on the client side with context.WithTimeout (or WithDeadline ) and handling codes.DeadlineExceeded . The server checks ctx.Deadline() or listens on ctx.Done() to abort long‑running work.
Overall, the article walks readers through building a complete gRPC system, covering protobuf definition, code generation for multiple languages, various RPC patterns, security with TLS, and robust timeout handling.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.