laravel中使用hprose实现一个简单的分布式应用
最近因为要写一个后台公司官网入口,小组长说试试用RPC写一下,基于本身用的是laravel框架,在网上找的资料少之又少,有的写的还是比较有用的,但不是很完全,我还是在基础之上慢慢摸索出来,下面是在laravel中结合hprose实现简单的分布式应用:
步骤1 引入hprose
在你的 laravel目录中的 composer.json 文件中,添加这部分::
{
"require": {
"hprose/hprose": ">=2.0.0"
}
}
然后在你的根目录使用composer update 命令下载 hprose 扩展包
步骤2 创建服务端
在你的app目录下 创建一个Services目录(可手动创建)
在目录下面创建UserService.php作为服务端,内容如下:
<?php
namespace App\Services;
use Hprose\Http\Server;
class UserService{
public function init(){
$server=new Server();
$server->addMethod('test',$this);
$server->start();
}
public function test(){
return 'hello';
}
}
步骤3 创建服务端路由
简单的服务端的代码就完成了,现在我们在api.php设置一下路由:
Route::post('service', function (Request $request) {//服务端一定用post不然会报错
$server = new \App\Services\UserService();
$server->init(); //开启服务
})->middleware('api');
测试:访问http://localhost/api/service,如果出现“Fa1{s5"test"}z”就表示方法是成功添加到服务了。
猜测这个序列化结果的含义:
F表示function;a表示List/Array;1表示List/Array的长度;{和}是分隔符,便于解析;s表示String;4表示后接string的长度;z表示end。
步骤4 创建客户端
这边我还是以laravel框架创建客户端为例。
还是在Service目录下面新建文件UserClien.php作为客户端,内容如下:
<?php
namespace App\Services;
use Hprose\Http\Client;
class UserClien
{
public function index($request){
//服务端路由在api路由中配置,则此处路由应加上api/test
//实例化可选参数 加上false 即创建创建一个同步的 HTTP 客户端
//不写false 为创建一个异步的 HTTP 客户端
$user =new Client('http://localhost/api/service',false);
$res=$user->test();
dd($res);
}
}
步骤5 创建客户端路由
在web.php中添加
Route::post('Clien', function () {
$server = new \App\Services\UserClien();
$server->index();
});
测试:访问http://localhost/clien,如果输出“hello”就表示简单的分布式应用就开发好了。
**注意:**如要转载,请标明内容出处。