PHP asynchronous operations _ PHP Tutorial

Source: Internet
Author: User
Tags php cli
PHP implements asynchronous operations. 1. Why does PHP require asynchronous operations? In general, PHP is applicable to web page display tasks that are time-consuming. if you want to perform time-consuming operations such as resize images, big data import, and 1. Why does PHP need asynchronous operations?

In general, PHP is applicable to web page display tasks that are time-consuming. if you want to perform time-consuming operations such as resize images, big data import, batch sending of EDM and SMS, it is easy to see Operation timeout. You can say that I can set an infinite timeout. wait, you also need to know that PHP has a working mode that is fastcgi, and PHP does not time out infinitely. it does not mean that fastcgi does not time out ...... If you want to say fastcgi never times out, I suggest you discuss it with your O & M personnel ......

At this time, the asynchronous operation will play its role. because of the non-blocking operation, the operation will return immediately and then work slowly in the background. If you do not time out, I will not work in the current process/thread. Check whether it is beautiful, but it is actually a pitfall ......

2. can PHP implement asynchronous operations?

The answer is yes, but the pure PHP implementation on the Internet is a bit awkward. Socket mode, pending process mode, and some directly fork processes. Good. all the gods see each other. If the O & M personnel see this, they will certainly be xxx yours. it's strange not to run the web server to death ......

Is there any other better way to implement this asynchronous operation? Yes. now we only want to open plug-ins. Check that there are a bunch of ×× MQ (Message Queue) plug-ins in main PECL plug-ins. one plug-in used for task allocation comes into our sight, Gearman (in fact, this guy is the horn, I will not introduce it in detail. Click Connect to see the introduction ).

3. Why choose Gearman?

If you don't talk about anything else, it means that there are many clients that support many languages. you can use most of your favorite languages to write worker. Personally, I am very tired of language competition. you like to write worker in the CAPTCHA language as you like. Support for data persistence (that is, saving the queue to the database medium, and fault recovery) and cluster support (in fact many ×× MQ have these features ). PECL has extensions and pure PHP extensions. This Gearman has been active for a long time, and the problem is basically solved.

4. basic ideas

With Gearman, this plug-in is much simpler. It is to send a task to gearman, send the executed task, and then wait for worker to call PHP cli to run our php code.

I wrote a python worker (don't ask why I use python, 1. I will use python, 2. in linux, you don't need to install runtime. you can write a PHP worker based on your own ideas. However, I don't really trust the worker that PHP runs. You can use java, node. js, or other languages to implement a worker. If you are interested in using Golang to write worker, contact me.

Phpasync_worker_py

Sorry, there is no comment in it. A configuration file and a py script. The basic function is to analyze the called parameters and then call PHP Cli. To run the py script, install the python gearman module.

Then test the code in the PHP section:

 
  1.    
  2. Require_once 'phpasyncclient. php ';
  3. Date_default_timezone_set ('Asia/Shanghai ');
  4. Class AsyncTest {
  5. Const
  6. LOG_FILE = '/debug. log ';
  7. Static public function run (){
  8. If (PHPAsyncClient: in_callback (_ FILE __)){
  9. Self: log ('php Async callback ');
  10. PHPAsyncClient: parse ();
  11. Return;
  12. }
  13. If (PHPAsyncClient: is_main (_ FILE __)){
  14. Self: log ('main run ');
  15. $ Async_call = PHPAsyncClient: getInstance ();
  16. $ Async_call-> AsyncCall ('asynctest', 'callback', array (
  17. 'Content' => 'Hello World !!! ',
  18. ), Array (
  19. 'Class' => 'asynctest ',
  20. 'Method' => 'callback ',
  21. 'Params' => array (
  22. 'Content' => 'Hello Callback! ',
  23. ),
  24. ), _ FILE __);
  25. Return;
  26. }
  27. }
  28. Static public function callback ($ args ){
  29. Self: log ('asynctest callback run ');
  30. Self: log ('asynctest callback args: '. print_r ($ args, true ));
  31. }
  32. Static public function log ($ content ){
  33. $ Fullname = dirname (_ FILE _). self: LOG_FILE;
  34. $ Content = date ('[Y-m-d H: I: s]'). $ content. "\ n ";
  35. File_put_contents ($ fullname, $ content, FILE_APPEND );
  36. }
  37. }
  38. AsyncTest: run ();

There are three static methods, one is the log method used for debugging, and the other is literal. This example gives a preliminary impression on this call method. Then directly go to all the PHP source code:

Php_async.zip

Then many people will say that gearman cannot be installed in win ...... So I will also release the gearman server for java.

Java-gearman-service-0.6.6.zip

5. Conclusion

After the above configuration of a guy with the same size as the rhinoceros (to install a Gearman and run a Py script), we basically made PHP have the Asynchronous call function, of course, there is also a state maintenance shenma to achieve it on its own. So we found that this solution is not so complicated. It would be better to use some web service methods to do web callback (the problem is that web callback times out ......), Please pay attention to the future.

Why? In general, PHP is applicable to web page display tasks that are time-consuming ,...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.