Skip to content

分布式客户端

Pavle Lee edited this page Jun 29, 2017 · 7 revisions

我们添加服务发现机制的同时,也添加了分布式客户端,使用方式如下。

1.配置客户端组件

'rpc' => [
    'class' => 'Hprose\Yii\RpcClient',
    //服务中心地址(也可以只包含一个)
    'discoverUrls' => [
        'http://service1.example.com/discovery/index',
        'http://service2.example.com/discovery/index',
        'http://service3.example.com/discovery/index',
        'http://service4.example.com/discovery/index',
    ]
]

客户端会并发的请求这4个服务中心,拉取列表做合并。比如:

//service1:
[
    'user' => 'http://service1.example.com/user/index',
    'payment' => 'http://service1.example.com/payment/index',
]

//service2:
[
    'user' => 'http://service2.example.com/user/index',
    'order' => 'http://service2.example.com/order/index',
]

//最终合并的配置为
[
    'user' => [
          'http://service1.example.com/user/index',
          'http://service2.example.com/user/index',
     ],
    'payment' => 'http://service1.example.com/payment/index',
    'order' => 'http://service2.example.com/order/index',
]

Hprose会通过负载的形式使用服务列表中的地址

2.使用服务

$user = Yii::$app->rpc->getService('user');
$user->create();

,配合服务文档,开发者可以很好的构建一个服务系统

3.定制客户端参数 我们知道你会想添加客户端参数或者配置一些别的东西,我们提供一个事件,你只需要给他绑定事件的处理函数即可

class AdornClientBehavior extends Behavior
{
    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            RpcClient::EVENT_AFTER_INIT_CLIENT=> 'adornClient'
        ];
    }

    /**
     * 装饰客户端
     */
    public function adornClient($event)
    {
        $client = $event->data;
        //$client就是客户端实例,你可以按照Hprose的文档随意装饰
        //由于$event->data是引用传递的,所以不需要return
    }
}
Clone this wiki locally