Another jet client for Hyperf
composer require "friendsofhyperf/jet:^3.0"
use FriendsOfHyperf\Jet\Metadata;
use FriendsOfHyperf\Jet\ServiceManager;
use FriendsOfHyperf\Jet\Registry\ConsulRegistry;
use FriendsOfHyperf\Jet\Transporter\GuzzleHttpTransporter;
$metadata = new Metadata('CalculatorService');
$metadata->setTransporter(new GuzzleHttpTransporter('127.0.0.1', 9502));
// or
$metadata->setRegistry(new ConsulRegistry(['uri' => 'http://127.0.0.1:8500']));
ServiceManager::register('CalculatorService', $metadata);
use FriendsOfHyperf\Jet\RegistryManager;
use FriendsOfHyperf\Jet\Registry\ConsulRegistry;
RegistryManager::register(RegistryManager::DEFAULT, new ConsulRegistry(['uri' => $uri, 'timeout' => 1]));
In Laravel project, Add to
boot()
inApp/Providers/AppServiceProvider.php
use FriendsOfHyperf\Jet\ClientFactory;
$client = ClientFactory::create('CalculatorService');
var_dump($client->add(1, 20));
use FriendsOfHyperf\Jet\ClientFactory;
return ClientFactory::create(function() {
return (new Metadata('CalculatorService'))
->setPacker(new GrpcPacker())
->setPathGenerator(new GrpcPathGenerator())
// If use consul next config is necessary
->setRegistry(RegistryManager::get(RegistryManager::DEFAULT))
->setTransporterConfig([
'path' => 'calculator.CalCulator',
])
->setProtocol('grpc')
->setTimeout(10)
// If not use consul,directly use GrpcTransporter
->setTransporter(new GrpcTransporter('127.0.0.1', 9502, [
'path' => 'calculator.CalCulator',
]));
});
use FriendsOfHyperf\Jet\Client;
use FriendsOfHyperf\Jet\Transporter\GuzzleHttpTransporter;
use FriendsOfHyperf\Jet\Registry\ConsulRegistry;
/**
* @method int add(int $a, int $b)
*/
class CalculatorService extends Client
{
public function __construct($service = 'CalculatorService')
{
$metadata = (new Metadata($service))
// Custom transporter
->setTransporter(new GuzzleHttpTransporter('127.0.0.1', 9502))
// Custom registry
->setRegistry(new ConsulRegistry(['uri' => 'http://127.0.0.1:8500']));
parent::__construct($metadata);
}
}
$service = new CalculatorService;
var_dump($service->add(3, 10));
use FriendsOfHyperf\Jet\Facade;
use FriendsOfHyperf\Jet\ClientFactory;
/**
* @method static int add(int $a, int $b)
*/
class Calculator extends Facade
{
protected static function getFacadeAccessor()
{
// return ClientFactory::create('CalculatorService');
return 'CalculatorService';
}
}
var_dump(Calculator::add(rand(0, 100), rand(0, 100)));
// config/autoload/annotations.php
<?php
declare(strict_types=1);
return [
'scan' => [
// ...
'class_map' => [
GuzzleHttp\Client::class => BASE_PATH . '/vendor/friendsofhyperf/jet/classmap/GuzzleHttp/Client.php',
],
],
];