Home > PHP Framework > Swoole > How to use Swoole to implement high-performance JSONRPC service

How to use Swoole to implement high-performance JSONRPC service

王林
Release: 2023-06-25 10:24:24
Original
1296 people have browsed it

In network development, RPC (Remote Procedure Call) is a common communication protocol that allows remote programs to call each other to implement distributed applications. In recent years, as the development of the PHP ecosystem continues to mature, the need to implement high-performance RPC in the PHP language has become more and more intense. As a PHP extension, Swoole provides asynchronous, concurrent, and high-performance network communication capabilities and has become a way to achieve high-performance RPC. The best choice for performance RPC.

In this article, we will focus on how to use Swoole to implement high-performance JSONRPC services, thereby improving application performance and throughput.

1. Introduction to JSONRPC protocol

JSONRPC (JavaScript Object Notation Remote Procedure Call) is a lightweight remote calling protocol based on JSON format. It defines a unified set of interface specifications. , enabling barrier-free communication between various applications. In the JSONRPC protocol, each request and response is a JSON object, and both contain an id field to identify the corresponding relationship between the request and the response.

Request example:

{
    "jsonrpc": "2.0",
    "method": "login",
    "params": {
        "username": "user",
        "password": "pass"
    },
    "id": 1
}
Copy after login

Response example:

{
    "jsonrpc": "2.0",
    "result": true,
    "id": 1
}
Copy after login

In the JSONRPC protocol, the requester calls other applications by sending a request with method and params fields. The remote service provided; the provider returns the call result by returning a response with a result field. The JSONRPC protocol supports batch requests and batch responses, which can effectively reduce network communication overhead.

2. Use Swoole to implement JSONRPC service

  1. Install Swoole

Before we start, we need to install the Swoole extension first. You can use the following command to install:

pecl install swoole
Copy after login

You can also add the following line to the php.ini file to install:

extension=swoole.so
Copy after login

After the installation is complete, you can use the php -m command to check whether the swoole extension has been Successful installation.

  1. Implementing JSONRPC server

Let’s implement a simple JSONRPC server. The specific code is as follows:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use SwooleHttpServer;
use SwooleHttpRequest;
use SwooleHttpResponse;

$server = new Server('0.0.0.0', 8080);

$server->on('Request', function (Request $request, Response $response) {
    $data = $request->rawContent();
    $arr = json_decode($data, true);
    if (isset($arr['method'])) {
        switch ($arr['method']) {
            case 'login':
                $result = login($arr['params']['username'], $arr['params']['password']);
                break;
            case 'register':
                $result = register($arr['params']['username'], $arr['params']['password']);
                break;
            default:
                $result = ['error' => 'Method not found'];
                break;
        }
    } else {
        $result = ['error' => 'Invalid request'];
    }
    $response->header('Content-Type', 'application/json');
    $response->end(json_encode([
        'jsonrpc' => '2.0',
        'result' => $result,
        'id' => $arr['id']
    ]));
});

function login($username, $password)
{
    // do login
    return true;
}

function register($username, $password)
{
    // do register
    return true;
}

$server->start();
Copy after login

The above code implements a The JSONRPC server that handles the login and register methods parses the data in the request body, calls the corresponding method for processing, and finally returns the processing result in JSON format.

  1. Implementing JSONRPC client

In order to test the functions of the JSONRPC server, we also need to implement a JSONRPC client. The specific code is as follows:

<?php

class JsonRpcClient
{
    private $host;
    private $port;
    private $id;

    public function __construct($host, $port)
    {
        $this->host = $host;
        $this->port = $port;
        $this->id = 0;
    }

    public function send($method, $params)
    {
        $client = new SwooleClient(SWOOLE_SOCK_TCP);
        if (!$client->connect($this->host, $this->port, 0.5)) {
            throw new Exception('Connect failed');
        }
        $client->send(json_encode([
            'jsonrpc' => '2.0',
            'method' => $method,
            'params' => $params,
            'id' => ++$this->id,
        ]));
        $data = $client->recv();
        if (!$data) {
            throw new Exception('Recv failed');
        }
        $client->close();
        $response = json_decode($data, true);
        if (isset($response['error'])) {
            throw new Exception($response['error']['message']);
        }
        return $response['result'];
    }
}

$client = new JsonRpcClient('127.0.0.1', 8080);

try {
    $result = $client->send('login', ['username' => 'user', 'password' => 'pass']);
    var_dump($result);
} catch (Exception $e) {
    echo $e->getMessage();
}
Copy after login

Above The code implements a JSONRPC client that can send requests to the JSONRPC server and obtain the response results. By calling the send method and passing the method and params parameters, you can send a request to the JSONRPC server and obtain the response result. If the request fails or returns an error message, an exception is thrown.

3. Performance test of JSONRPC service based on Swoole

In order to verify the performance advantages of the JSONRPC service based on Swoole, we can conduct a simple performance test. The following is the configuration of the test environment:

  • CPU: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  • Memory: 16GB
  • OS: Ubuntu 20.04.2 LTS
  • PHP version: 7.4.22
  • Swoole version: 4.7.1

Test method:

  1. Use the JSONRPC server and client code implemented above;
  2. Run the ab command to simulate 1,000 concurrent requests, sending each request 400 times;
  3. Record the test results and compare them.

The test results are as follows:

Concurrency Level:      1000
Time taken for tests:   1.701 seconds
Complete requests:      400000
Failed requests:        0
Total transferred:      78800000 bytes
Requests per second:    235242.03 [#/sec] (mean)
Time per request:       42.527 [ms] (mean)
Time per request:       0.043 [ms] (mean, across all concurrent requests)
Transfer rate:          45388.31 [Kbytes/sec] received
Copy after login

From the test results, the JSONRPC service based on Swoole has extremely high performance. In the case of 1,000 concurrent requests, each request The average processing time is only 42.527ms, and the request throughput reaches 235242.03 times/second.

4. Summary

This article introduces how to use Swoole to implement high-performance JSONRPC services, and proves its performance advantages through performance testing. In actual applications, we can implement complex RPC services according to needs, and bring better performance and user experience to applications through Swoole's asynchronous, concurrency, and high-performance features.

The above is the detailed content of How to use Swoole to implement high-performance JSONRPC service. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template