search
HomeBackend DevelopmentPHP TutorialDetailed explanation of popular rpc framework in php

Detailed explanation of popular rpc framework in php

Mar 19, 2018 pm 02:31 PM
phpframeDetailed explanation

What is the RPC framework? If RPC can be summarized in one sentence: Remote Procedure Call, then what is remote call? Usually we call a method in PHP, such as this function method: localAdd(10, 20). The specific implementation of the localAdd method is either defined by the user or comes with the PHP library function, that is, in the localAdd method The code is implemented locally, it is a local call! Remote calling means: the specific implementation of the called method is not where the program is running, but in some other remote place.

Remote calling principle

For example, A (client) calls the remoteAdd method provided by B (server):

  1. First, establish a connection between A and B TCP connection;

  2. Then A serializes the method name that needs to be called (remoteAdd here) and method parameters (10, 20) into a byte stream and sends it out;

  3. B accepts the byte stream sent by A, then deserializes it to obtain the target method name and method parameters, then executes the corresponding method call (possibly localAdd) and returns the result 30;

  4. A accepts the remote call result and outputs 30.

The RPC framework encapsulates the details I just mentioned and exposes users to simple and friendly API usage.

Benefits of remote calling

Decoupling: When the server needs to modify the method, the client is completely unaware and does not need to make any changes; this method is suitable for cross-department and cross-company cooperation. It is often used, and the provider of the method is usually called: service exposure.

What is the difference between RPC and Socket?

Through the above simple explanation, it seems that RPC and Socket are similar. They all call remote methods and are all in client/server mode. I also wrote an article before: Talking about sockets in detail. So what are the differences between them?

RPC (remote procedure call) uses client/server Mode enables two processes to communicate with each other. Socket is one of the communication methods often used by RPC. RPC is implemented on the basis of Socket. It requires more network and system resources than Socket. In addition to Socket, RPC also has other communication methods, such as http, the operating system's own pipeline and other technologies to implement calls to remote programs. In Microsoft's Windows system, RPC uses named pipes for communication.

What is the difference between RPC and REST?

After understanding RPC, we know that RPC is in client/server mode and calls remote methods. REST is also a set of API calling protocol methods that we are familiar with. It is also based on client/server mode and calls remote methods. method, so what’s the difference between them?

REST API and RPC both encapsulate functions into interfaces on the Server side and expose them for calls by the Client. However, the REST API is based on the HTTP protocol, and REST is committed to passing the POST/ GET/PUT/DELETE and other methods and a human-readable URL to provide an http request. RPC does not need to be based on the HTTP protocol
Therefore, if the two back-end languages ​​call each other, using RPC can achieve better performance (eliminating a series of things such as HTTP headers), and it should be easier to configure. If the front end calls the back end through AJAX, it is better to use the REST API (because you cannot avoid the HTTP hurdle anyway).

Since php is the best language in the world, what are the popular RPC frameworks in php?

Let’s list them first: phprpc, yar, thrift, gRPC, swoole, hprose

Because time and energy are limited, it is impossible to learn and use them one by one. I will choose a few that are commonly used in the world. Let’s use the ones with the most. Because the principle of RPC is the same, both are Client/Server mode, but the usage of each framework is different.

Mainly explain phprpc and yar, which I have heard about and come into contact with the most so far.

phprpc

First download the latest stable version of phprpc from the official website: download link and unzip.

Installation

We will find that there are many files and folders inside, with the following structure:

  • dhparams/

  • pecl/

  • bigint.php

  • compat.php

  • phprpc_date.php

  • xxtea.php

  • ##dhparams.php

  • phprpc_server.php

  • phprpc_client.php

Among them, dhparams and pecl are folders, and pecl is the xxtea extension of php, as described on the official website , you can install it or not, and it can run without installing phprpc. But if you need faster encryption processing capabilities, you can install it.

I’d better install it. After all, the encryption capability is faster, which is a good thing:

The installation steps are as follows, first copy the xxtea folder under pecl to the etx directory of the php source code: /lamp/php-5.4.11/ext. Then use phpize to recompile with extensions.

[root@localhost /]# cd /lamp/php-5.4.11/ext/xxtea
[root@localhost xxtea]# /usr/local/php/bin/phpize
[root@localhost xxtea]# ./configure --enable-xxtea=shared --with-php-config=/usr/local/php/bin/php-config
make && make install

OK, the compilation is completed, prompting us that xxtea.so is already in /usr/local/php/lib/php/extensions/no-debug-zts-20100525/xxtea.so.

Next, we need to add this xxtea.so at the end of php.ini:

[root@localhost /]# vi /usr/local/php/etc/php.ini 
[xxtea]
extension=xxtea.so

Okay. After adding it, we need to restart apache or php-fpm

重启apache
[root@localhost /]# /usr/local/apache/bin/apachectl restart
平滑重启php-fpm
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`

After the restart, open the phpinfo() page, search, and you should be able to see xxtea.

Start using

Let’s take a simple example first. phprpc is also divided into server and client. So the corresponding files in the folder are phprpc_server.php and phprpc_client.php

Let’s refer to several examples on the official website and practice:

server.php Server side: Writing this way will complete a final Simple helloword interface.

<?php
include ("phprpc/phprpc_server.php");
function HelloWorld() {
   return &#39;Hello World!&#39;;
}
$server = new PHPRPC_Server();
$server->add(&#39;HelloWorld&#39;);
$server->start();

Run server.php, I wiped it, and an error was reported! ! !

PHP Strict Standards:  Non-static method PHPRPC_Server::initSession()....
Cannot redeclare gzdecode().....

Googled it, and it said that they first changed the initSession() in line 413 of phprpc_server.php to a static function

 static function initSession() {
    ****
 }

PS. I was surprised, such a big mistake, phprpc is How to publish it! ! !

In the gzdecode() function on line 71 of compat.php, php5.4 has already implemented this function. In this way, the function is rewritten and an error is reported, so add a judgment:

if (!function_exists('gzdecode')) {
    //将gzdecode函数包括进来
}

Okay. After making changes, save. Run server.php again. OK. No more errors. Output:

phprpc_functions="YToxOntpOjA7czo5OiJoZWxsb3dvcmQiO30=";

Let’s write the client client.php next. Let’s see how it is written?

<?php
include ("phprpc/phprpc_client.php");
$client = new PHPRPC_Client(&#39;http://127.0.0.1/server.php&#39;);
echo $client->HelloWorld();
?>

We are executing the following client.php, and the output is as expected:

Hello Word!

Such a simple Server/Clent delivery is completed. Although there were some mistakes in the middle, it is generally quite simple and easy to understand!

For other more advanced usage, please refer to the official website.

yar

yar is the masterpiece of Hui Xinchen, the famous PHP master in China, and has been used in Weibo products. It is also an rpc framework. Because it uses an extension for PHP written in pure C, the efficiency should be quite high, and it supports asynchronous parallelism, which is quite good.

Download and install

Official website download: http://pecl.php.net/package/yar The latest version yar-1.2.4.tgz

Then unzip and copy to The etx directory of the php source code: /lamp/php-5.4.11/ext. Then use phpize to recompile with extensions.

[root@localhost yar-1.2.4]# /usr/local/php/bin/phpize
[root@localhost yar-1.2.4]# ./configure --with-php-config=/usr/local/php/bin/php-config

But there is a problem: prompt, there is a problem with curl:

configure: error: Please reinstall the libcurl distribution - easy.h should be in <curl-dir>/include/curl/</curl-dir>

It is estimated that there is a problem with my local curl, then use yum to install it:

yum -y install curl-devel

Installation After completing curl, continue compiling and installing, and there will be no problem:

[root@localhost yar-1.2.4]# /usr/local/php/bin/phpize
[root@localhost yar-1.2.4]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@localhost yar-1.2.4]# make && make install

After success, we will be prompted that the yar.so extension is already in /usr/local/php/lib/php/extensions/no-debug-zts -20100525/ is down.

We vi edit php.ini, add the yar.so extension at the end, and then restart apache or php-pfm.

[root@localhost /]# vi /usr/local/php/etc/php.ini 
[yar]
extension=yar.so

Okay. After adding it, we need to restart apache or php-fpm

重启apache
[root@localhost /]# /usr/local/apache/bin/apachectl restart
平滑重启php-fpm
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`

After the restart, open the phpinfo() page, search, and you should be able to see yar.

Start using

Like other rpc frameworks, yar is also in server/client mode, so we will do the same and start writing a simple example to show how to call it.

yar_server.php represents the server side

<?php
class API {
   public function api($parameter, $option = "foo") {
       return $parameter;
   }
   protected function client_can_not_see() {
   }
}
$service = new Yar_Server(new API());
$service->handle();

Okay, let’s run it in the browser, and the output as shown below will appear. Very high-end! ! ! Brother Niao said that the purpose of this is to know at a glance how many interfaces my rpc provides, and the api documentation can be omitted.

Detailed explanation of popular rpc framework in php

Okay, let’s start writing yar_client.php. This is the client:

$client = new Yar_Client("http://127.0.0.1/yar_server.php");
echo $client->api(&#39;helo word&#39;);

Okay, like other swoole, hprose, etc., this principle is basically the same. It just depends on which one has more functions and is easier to use.

Related recommendations:

The RPC framework in PHP implements a flow control system based on Redis

Detailed examples of RPC framework

Detailed code explanation of PHP remote calling and RPC framework (picture)

The above is the detailed content of Detailed explanation of popular rpc framework in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use