* Why and How to utilize asynchronous in PHP
* How to implement a simple asynchronous server with PHP C extension
* Production ready, large-scale asynchronous programming with PHP language and Swoole
Traditional PHP model • LNMP (LAMP): Linux, Nginx, MySQL, PHP-FPM • Originally created as a templating language • Thread/process based model • Blocking IO and Sync • Stateless and scalable • FastCGI • Process per connection is memory expensive • Build up everything then destroy everything • Triggered by user request (No scheduler) • Process per connection is easy for 504 timeout
1.Receive the request 2.Load and compile files and codes 3.Initialize the objects and variables 4.Execute the functions 5.Send the response 6.Recycle the resources The life cycle of HTTP request in PHP
Pros and Cons of PHP Pros Cons Simple and easy No IoT (asynchronous I/O) Huge Ecosystem Difficult to implement Server side protocol and services: TCP Socket, SMTP, MQTT, WebSocket, Thrift, etc Sync Simple and easy Sync One wait stop all Stateless Stateless Scalable Low performance Robust No long-live connection No pooling
How to do async tasks Message Queue or Task Queue Restful services or RPC Ajax CURL Fork a new process/thread CRON vs I/O multiplexing, Non-blocking I/O, IPC
Linux I/O multiplexing, non-blocking • select() monitors the sockets’ status flag and return the status of all sockets, manually iterate through all the fds (C10K problem) • poll() similar to select() but allocate an array of pollfd, can handle more than 1024 sockets •epoll() monitors sockets’ status and trigger related events, and only return triggered events array.
The problems we like to sort out for PHP • High concurrency, large number of connections • Long-live connections, real-time services • Long-live connections to DB, Cache, RPC etc • Support more server side protocols • Server side programming • Scheduler • Async tasks need 3rd party services • Manage and reuse the status in memory • Performance
1.Receive the request 2.Load and compile files and codes 3.Initialize the objects and variables 4.Execute the functions 5.Send the response 6.Recycle the resources The life cycle of HTTP request in PHP
1.Load and compile files and codes 2.Initialize the objects and variables 3.Receive the request 4.Execute the functions 5.Send the response 6.Recycle the resources The life cycle of HTTP request in PHP
But it opens the door for PHP developers: • RPC server • Websocket server • TCP server • High performance services • High concurrency systems (C100K) • Internet of things server • Compete with language X, Y, Z