JsonRpc 调用

2018/04/24 PHP

介绍

json-rpc是基于json的跨语言远程调用协议,比xml-rpc、webservice等基于文本的协议传输数据格小;相对hessian、java-rpc等二进制协议便于调试、实现、扩展,是非常优秀的一种远程调用协议。目前主流语言都已有json-rpc的实现框架,java语言中较好的json-rpc实现框架有jsonrpc4j、jpoxy、json-rpc。三者之中jsonrpc4j既可独立使用,又可与spring无缝集合,比较适合于基于spring的项目开发。

使用到的composer 包

fguillot/json-rpc : https://packagist.org/packages/fguillot/json-rpc

php 使用

Installation with Composer

composer require fguillot/json-rpc @stable

Examples

服务器端 回调绑定:

<?php

use JsonRPC\Server;

$server = new Server();
$server->getProcedureHandler()
    ->withCallback('addition', function ($a, $b) {
        return $a + $b;
    })
    ->withCallback('random', function ($start, $end) {
        return mt_rand($start, $end);
    })
;

echo $server->execute();

Class/Method binding:

<?php

use JsonRPC\Server;

class Api
{
    public function doSomething($arg1, $arg2 = 3)
    {
        return $arg1 + $arg2;
    }
}

$server = new Server();
$procedureHandler = $server->getProcedureHandler();

// Bind the method Api::doSomething() to the procedure myProcedure
$procedureHandler->withClassAndMethod('myProcedure', 'Api', 'doSomething');

// Use a class instance instead of the class name
$procedureHandler->withClassAndMethod('mySecondProcedure', new Api, 'doSomething');

// The procedure and the method are the same
$procedureHandler->withClassAndMethod('doSomething', 'Api');

// Attach the class, the client will be able to call directly Api::doSomething()
$procedureHandler->withObject(new Api());

echo $server->execute();

服务器中间件: 中间件可能用于认证和授权客户端。它们在每个过程之前执行。

<?php

use JsonRPC\Server;
use JsonRPC\MiddlewareInterface;
use JsonRPC\Exception\AuthenticationFailureException;

class Api
{
    public function doSomething($arg1, $arg2 = 3)
    {
        return $arg1 + $arg2;
    }
}

class MyMiddleware implements MiddlewareInterface
{
    public function execute($username, $password, $procedureName)
    {
        if ($username !== 'foobar') {
            throw new AuthenticationFailureException('Wrong credentials!');
        }
    }
}

$server = new Server();
$server->getMiddlewareHandler()->withMiddleware(new MyMiddleware());
$server->getProcedureHandler()->withObject(new Api());
echo $server->execute();

您可以AuthenticationFailureException在API凭证错误时提出申请,或者AccessDeniedException在用户不被允许访问该程序时提出申请。

客户端 Example with positional parameters:

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$result = $client->execute('addition', [3, 5]);

带有命名参数的示例

<?php

use JsonRPC\Client;

$client = new Client('http://localhost/server.php');
$result = $client->execute('random', ['end' => 10, 'start' => 1]);

完整例子

Server

Client

post url:

minsongtao.test.com/client.php

//Out put

Array ( [code] => 200 [data] => 69 )

其他客户端调用(such as: postman)

可见PHP调用相对于其他支持原生jsonrpc调用的客户端来说,做了一层封装,无论是在Client还是Server,参数结果的返回都显得更加简单明了。

一点小小的例子,希望对各位有点帮助。

Search

    Post Directory