php+nginx实现最简单的远程调用rpc

发布时间 2023-12-25 16:50:46作者: 冯元春

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 ["code"=>0,"message"=>"成功","data"=>$data];
    }
}

htpp端口设置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端口启动一下