PHP code example of huo-zi / laravel-yar-rpc-client

1. Go to this page and download the library: Download huo-zi/laravel-yar-rpc-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

huo-zi / laravel-yar-rpc-client example snippets


return [
    // Facade 类生成的命名空间
    'namespace' => 'App\\Rpc\\Clients\\',

    // 全局配置
    'options' => [
        // 调用超时时间(毫秒)
        \YAR_OPT_TIMEOUT => 5000,

        // 连接超时时间(毫秒)
        \YAR_OPT_CONNECT_TIMEOUT => 1000,

        // 序列化方式:php, json, msgpack
        \YAR_OPT_PACKAGER => 'php',

        // 是否启用 HTTP Keep-Alive
        \YAR_OPT_PERSISTENT => true,
    ],

    // RPC 客户端配置
    'clients' => [
        'user' => [
            'url' => 'http://api.example.com/user',
            // 客户端级配置(可选,会覆盖全局配置)
            'options' => [
                \YAR_OPT_TIMEOUT => 3000,
            ],
        ],
        'order' => [
            'url' => 'http://api.example.com/order',
        ],
    ],
];

use App\Rpc\Clients\UserRpcClient;
use App\Rpc\Clients\OrderRpcClient;

// 调用远程方法
$user = UserRpcClient::getUser(1);
$users = UserRpcClient::listUsers(['page' => 1, 'limit' => 10]);

// 调用订单服务
$order = OrderRpcClient::getOrder(123);

use App\Rpc\Clients\ConcurrentRpcClient;

// 并发调用多个服务(魔术方法方式)
$result = ConcurrentRpcClient::user('getUser', [1])
    ->order('getOrder', [123])
    ->execute();

// 获取结果
$user = $result->get('user.getUser');
$order = $result->get('order.getOrder');

use App\Rpc\Clients\ConcurrentRpcClient;

// 并发调用多个服务(call() 方法方式)
$result = ConcurrentRpcClient::call('user', 'getUser', [1])
    ->call('order', 'getOrder', [123])
    ->execute();

// 获取结果
$user = $result->get('user.getUser');
$order = $result->get('order.getOrder');

// 成功示例
[
    'user.getUser' => [
        'code' => 0, // 0 表示成功
        'data' => $userData // 远程方法返回的数据
    ],
    'order.getOrder' => [
        'code' => 0,
        'data' => $orderData
    ]
]

// 失败示例(某个服务调用失败)
[
    'user.getUser' => [
        'code' => 0, // 成功
        'data' => $userData
    ],
    'order.getOrder' => [
        'code' => 1, // 失败,yar错误码
        'message' => 'Connect timeout' // 错误信息
    ]
]

// 服务容器键名格式
app('rpc.client.user');
app('rpc.client.order');
bash
php artisan vendor:publish --provider="Huozi\Yar\Rpc\Client\ServiceProvider"
bash
php artisan make:rpc_facade
bash
php artisan clear-compiled