Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
OpenSwoole 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.
You have to install OpenSwoole GRPC library with
composer require openswoole/grpc
to use this hook.
Then you can generate PHP stub codes from the .proto
and OpenSwoole GRPC Compiler.
Then implement the logic of the client in the generated PHP service files like the following Helloworld GreeterClient example:
<?php
declare(strict_types=1);
// src/Helloworld/GreeterClient.php
namespace Helloworld;
class GreeterClient extends \OpenSwoole\GRPC\BaseStub
{
/**
* @param mixed $metadata
*
* @throws \OpenSwooleGRPC\Exception\InvokeException
*/
public function SayHello(HelloRequest $request, $metadata = []): HelloReply
{
return $this->_simpleRequest('/helloworld.Greeter/SayHello',
$request,
['\Helloworld\HelloReply', 'decode'],
$metadata);
}
}
<?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";
});