Introducing OpenSwoole 2022 GRPC

Published:

Open Swoole GRPC for PHP version 2022 is a high-performance integration solution for building cloud-native multiple language microservices architecture.

Introducing OpenSwoole 2022 GRPCIntroducing OpenSwoole 2022 GRPC

What is GRPC?

gRPC is a cross-platform open-source high-performance Remote Procedure Call framework created by Google. Used to connect the large number of microservices running within and across its data centres for over a decade.

Why and When to use GRPC?

Compared with REST on HTTP/1.1, gRPC uses a more modern HTTP/2 with multiplexed streaming and binary protocol framing.

GRPC can be used for large-scale microservices connections, real-time communication, low-power, low-bandwidth systems, and multi-language environments.

You can connect multiple programming languages or frameworks, and different systems with GRPC. It is a handy framework for software architects.

How OpenSwoole 2022 GRPC works

OpenSwoole provides the following GPRC components:

  • GRPC Server is the server side of OpenSwoole GRPC for PHP.
  • GRPC Client can be used to connect with GRPC services provided by either OpenSwoole GRPC servers or GRPC services implemented with other frameworks and programming languages.
  • GRPC Compiler can be used to generate PHP stub codes for your protocols.

Steps to create a GRPC service

Define Protocol Buffers protocols of your service

When implementing a GRPC service running on a PHP GRPC server, you get started with .proto file with the definition of the service.

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

service Stream {
  rpc FetchResponse (HelloRequest) returns (stream 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;
}

Generate PHP stub codes with OpenSwoole GRPC Compiler and add your logic

You can generate PHP stub codes from the .proto and OpenSwoole GRPC Compiler.

Then implement the logic of the service in the generated PHP service files like the following Helloworld GreeterService example:

<?php
# src/Helloworld/GreeterService.php
namespace Helloworld;

use OpenSwoole\GRPC;

class GreeterService implements GreeterInterface
{
    /**
     * @throws GRPC\Exception\InvokeException
     */
    public function SayHello(GRPC\ContextInterface $ctx, HelloRequest $request): HelloReply
    {
        $name = $request->getName();
        $out  = new HelloReply();
        $out->setMessage('hello ' . $name);
        return $out;
    }
}

Start OpenSwoole GRPC server

You can optionally add middlewares and process level contexts such as connection pools:

<?php

use Helloworld\GreeterService;
use Helloworld\StreamService;
use OpenSwoole\GRPC\Middleware\LoggingMiddleware;
use OpenSwoole\GRPC\Middleware\TraceMiddleware;
use OpenSwoole\GRPC\Server;

// enable hooks on IO clients
co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_ALL]);

$server = (new Server('127.0.0.1', 9501))
    ->register(GreeterService::class)
    ->register(StreamService::class)
    ->withWorkerContext('worker_start_time', function () {
        return time();
    })
    // use middlewares
    ->addMiddleware(new LoggingMiddleware())
    ->addMiddleware(new TraceMiddleware())
    ->set([
        'log_level' => \OpenSwoole\Constant::LOG_INFO,
    ])
    ->start();

Use your GRPC service at the client side

You can use any GRPC client to send requests to an OpenSwoole GRPC service. Or use the OpenSwoole GRPC client:

<?php
declare(strict_types=1);

use Helloworld\HelloRequest;
use OpenSwoole\Constant;
use OpenSwoole\GRPC\Client;

co::set(['log_level' => Constant::LOG_ERROR]);

co::run(function () {
    $conn    = (new Client('127.0.0.1', 9501))->connect();
    $client  = new Helloworld\GreeterClient($conn);
    $message = new HelloRequest();
    $message->setName(str_repeat('x', 10));
    $out = $client->sayHello($message);
    var_dump($out->serializeToJsonString());
    $conn->close();
    echo "closed\n";
});

You can also take the advantage of gRPC client side connection pools and reuse connections with OpenSwoole generic connection pool in version 2022.

Stay tuned

OpenSwoole GRPC 2022 is not released yet at the date of writing this article. Stay tuned for the upcoming release of OpenSwoole 2022. ⚡️