Home  >  Article  >  PHP Framework  >  Quick introduction to sharing the principles of Swoole engine

Quick introduction to sharing the principles of Swoole engine

coldplay.xixi
coldplay.xixiforward
2021-03-12 11:01:181991browse

Quick introduction to sharing the principles of Swoole engine

In the past six months, I have completed a game server project using PHP and Java technology stacks. Since there are high-frequency network requests in the project, the PHP technology stack tried to use the Swoole engine (a high-performance event-based asynchronous parallel network communication engine) to complete part of the game business.

Recommended (free): swoole

Swoole installation

Installing swoole is very simple, Since it is a project done by Chinese people, answers to many issues can be found in the official website documents. There are two types of installation:

  • Compile and install. Go directly to github or gitee to download the official release version. After compiling and installing, write the so extension into the php.ini file.
  • Container installation. The swoole engine is widely used, so there are many containers available on the hub. Just select the one you need and pull it.

Just click on Baidu for specific instructions. There is a lot of related content on the Internet.

Advantages of Swoole engine

  1. Resident memory. In traditional PHP frameworks or single files, before processing each request, the operations of loading the framework file and configuration must be done. After the request is completed, all resources and memory will be released, so there is no need to worry about memory leaks. However, if the number of requests increases and concurrency is high, resources are created quickly and released immediately, which will cause the operating efficiency of the PHP program to drop sharply. Using Swoole does not have this problem: after the PHP code is loaded into the memory, it has a longer life cycle, so the database connection and other large objects established in this way will not be released. Each request only needs to process a small amount of code, and this code is only compiled by the PHP parser and resides in memory the first time it is run. In the future, OPCODE will be loaded directly to let the Zend engine run directly. In addition, things that PHP could not implement before, such as database connection pool and cache connection pool, can be implemented under the Swoole engine. The operating efficiency of the system will be greatly improved.
  2. Rapid development. The Swoole engine provides an asynchronous multi-threaded server in PHP language, asynchronous TCP/UDP network client, asynchronous MySQL, asynchronous Redis, database connection pool, AsyncTask, message queue, millisecond timer, asynchronous file reading and writing, and asynchronous DNS query. Swoole has built-in Http/WebSocket server/client and Http2.0 server.
  3. Coroutine programming model. Swoole4 can implement asynchronous programs using fully synchronous code. There is no need to add any additional keywords to the PHP code. The bottom layer automatically performs coroutine scheduling to implement asynchronous IO.

Swoole engine process analysis

The flow chart of Swoole operation is as follows:

Quick introduction to sharing the principles of Swoole engine

Threads or processes in Swoole

The structure diagram is as follows:

Quick introduction to sharing the principles of Swoole engine

##The Swoole engine is divided into two modes: single-threaded mode and process mode. This article only discusses process mode. The specific differences between the two are explained in the official documentation.

Master process

is used to handle swoole core events, such as connections from clients and local communication pipes. There are multiple threads in the master process, and each thread runs an instance of the epol function. (Since the Worker process is not forked by the Master process, the Worker process may still exist after forcibly killing the Master process)

Reactor thread

Swoole's main process is a multi-thread program of. There is a very important group of threads called Reactor threads. It is the thread that actually handles TCP connections and sends and receives data.

After accepting a new connection, Swoole's main thread will assign the connection to a fixed Reactor thread, and this thread will be responsible for monitoring the socket. Read the data when the socket is readable, perform protocol analysis, and deliver the request to the Worker process. Send data to the TCP client when the socket is writable

Manager process

The worker/task processes in swoole are all fork and managed by the Manager process.

When the child process ends, the manager process is responsible for recycling the child process to avoid becoming a zombie process. And create a new sub-process
When the server is shut down, the manager process will send signals to all sub-processes to notify the sub-processes to shut down the service
When the server reloads, the manager process will shut down/restart the sub-processes one by one

Worker process

Swoole provides a complete process management mechanism. When the Worker process exits abnormally, such as a fatal PHP error, being accidentally killed by other programs, or exiting normally after reaching the max_request number. The main process will restart the new Worker process. Code can be written in the Worker process like ordinary apache php or php-fpm. There is no need to write asynchronous callback code like Node.js.

Callback function of each process

Callback function in Master:

    onStart
  • onShutdown
Callback function in the Worker process

    onWorkerStart
  • onWorkerStop
  • onConnect
  • onClose
  • onReceive
  • onFinish
Callback function within the TaskWorker process

  • onTask
  • onWorkerStart

Callback function in the Manager process

  • onManagerStart
  • onManagerStop

The relationship between Reactor, Worker and TaskWorker

It can be understood that Reactor is nginx and Worker is php-fpm. The Reactor thread processes network requests asynchronously and in parallel, and then forwards them to the Worker process for processing. Reactor and Worker communicate through UnixSocket.
In php-fpm applications, a task is often delivered asynchronously to a queue such as Redis, and some PHP processes are started in the background to process these tasks asynchronously. TaskWorker provided by Swoole is a more complete solution that integrates task delivery, queue, and PHP task processing process management. Asynchronous task processing can be implemented very simply through the API provided by the underlying layer. In addition, TaskWorker can also return a result to the Worker after the task execution is completed.
Swoole's Reactor, Worker, and TaskWorker can be closely combined to provide more advanced usage methods. A more popular metaphor: Assume that the Swoole application server is a factory, and the Reactor is sales, accepting customer orders. The Worker is the worker. When the salesperson receives the order, the Worker goes to work to produce what the customer wants. The TaskWorker can be understood as an administrative staff, which can help the Worker do some chores so that the Worker can concentrate on work.
The bottom layer will assign a unique ID to the Worker process and TaskWorker process. Different Worker and TaskWorker processes can communicate through the sendMessage interface.

The division of labor of each process thread in the actual project:

  • Manager process: responsible for managing worker processes, creating or recycling
  • Worker processes : Game logic processing
  • taskWorker process: sending network packets to the client, closing long-term inactive tcp connections

Swoole version compatibility

The swoole engine version used in the development stage of this project was 1.9.6. Later, because the test environment was installed to version 4.3.2, we tried to adjust the business code. However, the backward compatibility of swoole is very admirable. In this process, only one code incompatibility problem was discovered: a configuration parameter related to swoole_server. In the original version, it was configured using devil numbers, but in the new version Version, this number was not macro-defined. Later, I found the macro definition group by checking the swoole source code, and then modified this configuration. (However, the smooth version upgrade is also based on swoole's relatively small business code, so it is for reference only

More related learning recommendations:swoole tutorial

The above is the detailed content of Quick introduction to sharing the principles of Swoole engine. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete