In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what are the advantages of the combination of PHP and Go". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
General PHP development environment
Before I talk about how Go can improve the PHP death model, take a look at the regular PHP development environment.
Typically, applications run on nginx and PHP-FPM. Nginx handles static requests, while dynamic requests are redirected to PHP-FPM, which executes PHP code. Maybe you use Apache and mod_php, but they work on the same principle and work only slightly differently.
See how PHP-FPM executes the code. When a request is received, PHP-FPM initializes the PHP child process and forwards the details of the request to it as part of its state (_ GET, _ POST, _ SERVER, etc.).
The state cannot be changed during the execution of the PHP script, so there is only one way to get a new set of input data: clear the process memory and initialize it again.
This performance model has many advantages. You don't need to worry too much about memory consumption, all processes are completely isolated, and if one of the processes "dies", it will be automatically recreated and will not affect other processes. However, this approach has drawbacks when you try to extend the application.
Shortcomings and inefficiencies of typical PHP environments
If you are a professional developer of PHP, then you know where to start to create a new project-choose a framework. It is a library for dependency injection, ORM, transformation, and template methods. Of course, all the data entered by the user can be easily placed in an object (Symfony / HttpFoundation or PSR-7). These frames are great!
But everything has its price. In any enterprise framework, in order to handle a simple user request or access a database, you must load at least dozens of files, create many classes, and parse multiple configurations. But worst of all, after each task is complete, you need to reset everything and restart it: all the code you just started will become useless, and with its help, you won't be able to process another request. Tell this to any programmer written in another language-you'll see the confusion on his face.
For years, PHP engineers have been looking for solutions to this problem, using delayed loading techniques, microframes, optimization libraries, caching, and so on. But in the end, you still have to give up the entire application and start over *. With the preloading in PHP7.4, this problem will be partially resolved.
Can a PHP process handle multiple requests?
You can write PHP scripts that last more than a few minutes (hours or days at most): for example, Cron tasks, CSV parsers, queue handlers. All this work follows a pattern: they get a task, finish processing it, and then get the next task. The code is resident in memory, thus avoiding additional operations to load frameworks and applications, saving valuable time.
But it's not that easy to develop long-running scripts. Any error will kill the process, a memory overflow will cause a crash, and F5 can no longer be used to debug the program.
Things have improved since PHP 7: a reliable garbage collector has emerged, it has become easier to handle errors, and kernel extensions can avoid memory leaks. Yes, engineers still need to deal with memory carefully and remember the status in the code (which language allows you not to pay attention to these things? (of course, in PHP 7, there are not many surprises.
Can a model of resident PHP scripts be used to handle more trivial tasks such as HTTP requests, eliminating the need to download everything from scratch for each request?
To solve this problem, you first need to implement a server application that can receive HTTP requests and redirect them one by one to PHP worker instead of killing it every time.
We know that we can write web servers in pure PHP (PHP-PM) or C # extensions (Swoole). Although each method has its advantages, neither of these options is right for us-I want more. What we need is more than just a web server-- we want a solution that allows us to avoid problems associated with "restarting" in PHP while easily tuning and extending for specific applications. In other words, we need an application server.
Can Go help solve this problem? We know it can, because the language compiles the application into a single binary; it is cross-platform; it uses its own parallel processing model (concurrency) and libraries for processing HTTP; and finally, we can integrate more open source libraries into our programs.
Difficulties encountered in merging two programming languages
First, it is necessary to determine how two or more applications communicate with each other.
For example, using Alex Palaestras's go-php library, memory sharing can be achieved between PHP and Go processes, such as mod_php in Apache. But the functionality of this library limits our use of it to solve problems.
We decided to use a more common approach: to build interactions between processes by using sockets / pipelines. This approach has proved to be reliable over the past decade and has been well optimized at the operating system level.
First, we created a simple binary protocol for exchanging data between processes and handling transmission errors. In its simplest form, this type of protocol is similar to a netstring with a fixed-size packet header (17 bytes in our example) that contains information about the type of packet, its size, and the binary mask used to check the integrity of the data.
On the PHP side, we use the pack function, and on the Go side, we use the encoding / binary library.
One protocol is a little out of date for us, and we have added the ability to invoke net / rpc Go services directly from PHP. This feature will be of great help to us in later development, because we can easily integrate Go libraries into PHP applications. The results of this work can be seen in our other open source product, Goridge.
Assign tasks among multiple PHP Worker
After the implementation of the interaction mechanism, we began to think about how to better transfer tasks to the PHP process. When the task arrives, the application server must select an idle worker to execute it. If the worker process terminates or "dies" due to an error, we will clear it and create a new one. If the worker process executes successfully, we return it to the worker pool that can be used to execute the task.
To store the active worker process pool, we used a buffer channel, and in order to remove accidental "dead" worker processes from the pool, we added a mechanism to track errors and worker process status.
In the end, we have a runnable PHP server that can handle any request presented in binary form.
In order for our application to work as a web server, we must choose a reliable PHP standard to handle any incoming HTTP requests. In our example, we just need to convert a simple net / http request from Go to PSR-7 format so that it is compatible with most of the currently available PHP frameworks.
Because PSR-7 is considered immutable (some would say not technically), developers must write applications that do not treat requests as global entities in principle. This is fully in line with the concept of PHP resident process. Our final implementation (whose name has not yet been received) is as follows:
RoadRunner-High-performance PHP Application Server
Our first test task was an API backend where unpredictable burst requests occur periodically (more frequently than usual). Although nginx capabilities is sufficient in most cases, we often encounter 502errors because we are unable to balance the system quickly with the expected increase in load.
To solve this problem, we deployed the first PHP / Go application server in early 2018. And immediately achieved amazing results! We not only completely eliminated 502 errors, but also reduced the number of servers by 2/3, saving a lot of money and solving headaches for engineers and product managers.
In the middle of the year, we improved our scheme, released it on GitHub under MIT license and named it RoadRunner, thus emphasizing its amazing speed and efficiency.
How RoadRunner improves your development stack
The use of RoadRunner allows us to use the middleware net/http on the Go side, to validate JWT even before the request enters PHP, and to handle WebSocket and global aggregation status in Prometheus.
Thanks to the built-in RPC, you can open the API of any Go library in PHP without writing an extension pack. More importantly, with RoadRunner, you can deploy a new server that is different from HTTP. Examples include running the AWS Lambda processor in PHP, creating a powerful queue selector, and even adding gRPC to our application.
Using PHP and Go at the same time, the solution has been steadily improved, the application performance has been improved by 40 times in some tests, the debugging tools have been improved, the integration with Symfony framework has been realized, and support for HTTPS, HTTP/2, plug-ins and PSR-17 has been added.
This is the end of the content of "what are the advantages of the combination of PHP and Go". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.