php+nginx实现最简单的远程调用rpc(微服务) php
nginx配置,负载均衡
如果微服务只能远程调用一个服务端,那就失去意义了.用Nginx可以实现健康检测和负载均衡策略的配置.使得服务端具有扩展性和高可用性.
upstream userservice {
server 127.0.0.1:9002;
server 127.0.0.1:9003;
}
server {
listen 80;
location / {
proxy_pass http://userservice;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
微服务端用webmen实现
IndexController
<?php
namespace app\controller;
use support\Request;
class IndexController
{
public function rpc(Request $request)
{
$class_name="app\\service\\".$request->post('class');
$obj=new $class_name;
$res=call_user_func_array([$obj,$request->post("method")], $request->post('params'));
return $res;
}
}
Service
<?php
namespace app\service;
use app\model\User;
use support\Model;
class My
{
public function mymethod($name){
$data="yout input name is ".$name;
return json_encode(["code"=>0,"message"=>"成功","data"=>$data]);
}
}
http端口设置9002
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
return [
'listen' => 'http://0.0.0.0:9002',
'transport' => 'tcp',
'context' => [],
'name' => 'webman',
'count' => 32,
'user' => '',
'group' => '',
'reusePort' => false,
'event_loop' => '',
'stop_timeout' => 2,
'pid_file' => runtime_path() . '/webman.pid',
'status_file' => runtime_path() . '/webman.status',
'stdout_file' => runtime_path() . '/logs/stdout.log',
'log_file' => runtime_path() . '/logs/workerman.log',
'max_package_size' => 10 * 1024 * 1024
];
启动webman
php start.php start -d
复制服务端项目,用9003端口启动一下
客户端用thinkphp 和 GuzzleHttp 实现
<?php
namespace app\rpc_service;
use GuzzleHttp\Client;
class UserService{
/**
* @param $class
* @param $method
* @param $params
* @return mixed
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function get($class,$method,$params=[]){
$client = new Client();
$res = $client->post("http://127.0.0.1:80/index/rpc",['form_params' => [
'class' => $class,
"method"=>$method,
"params"=>$params
]]);
$json=$res->getBody()->getContents();
return json_decode($json,true);
}
}
调用
<?php
namespace app\controller;
use app\BaseController;
use app\rpc_service\UserService;
use GuzzleHttp\Client;
class Index extends BaseController
{
public function hello()
{
$UserService=new UserService();
$res= $UserService->get("My","mymethod",["name"=>"xiang"]);
return json_encode($res);
}
}
{
"code": 0,
"message": "成功",
"data": "yout input name is xiang"
}
性能损耗
thinkphp本地 QPS 6000多
本地远程调用 QPS 4000多
标签: php