The principle and implementation of PHP asynchronous operation

Source: Internet
Author: User
Tags php cli

1. Why does PHP need to operate asynchronously?

In general, the application of PHP is a Web page display and other time-consuming tasks, if the comparison takes time to operate such as resize pictures, Big Data import, Batch send EDM, SMS, etc., it is very easy to appear operation timeout situation. You can say I can set unlimited timeout time, and so on you also need to know that PHP has a working mode is fastcgi,php Infinite does not timeout, does not mean that fastcgi corresponding does not time out ... If you want to say that you want to fastcgi the corresponding never timeout, I suggest you should discuss with your OPS staff ...

This time the asynchronous operation will play his role, due to the non-blocking operation, the operation will return immediately, and then work slowly in the background. If you don't time out, I'm not working under the current process/thread. See it is not very good, but in fact this is a pit ...

2.PHP can I implement asynchronous operations?

The answer is yes, but the net of all kinds of pure PHP implementation is a bit awkward. Socket mode, suspend process mode, and some also directly fork the process. Very good, each road immortal recount. If the Ops people see, will certainly xxxxx you, not to run the Web server to die just strange ...

Is there any better way to implement this asynchronous operation? There, now we only want to how to hang up. Check the PECL mainstream plug-in program has a bunch of xxmq (Message Queuing), which has a task to assign the plug-in into our line of sight Gearman (in fact, this guy is the angle, I do not detailed introduction, point of connection to see Introduction).

3. Why Choose Gearman?

In other words, say that he has more clients, support many languages of the client, you can use most of the language you like to write worker. I am a very annoying language struggle, you like to write in God code language workers are as you like. There are data persistence support (that is, to save the queue to the database media, the recovery is done), there is cluster support (in fact, many xxmq have these features). There are extensions on the pecl, as well as pure PHP implementations. Anyway, this gearman also lived for a long time, assorted's problems are basically solved.

4. Basic Ideas

With the Gearman this plug-in is much simpler. is to send a task to the Gearman, which sends out the task, and then waits for the worker to call the PHP CLI to run our PHP code.

I wrote a python worker (don't ask me why I use python,1. I will python,2.linux without the runtime), you can write a PHP worker according to your ideas, but, I am not very trustworthy PHP running worker. Other languages rice can be implemented in Java, node. js, or other languages to try out a worker. A friend who is interested in writing a worker with Golang can find me.

Phpasync_worker_py

Sorry, there is no comment inside. A configuration file, a PY script. The basic function is to analyze the parameters of the call and then invoke the PHP Cli, which is what it looks like. To get the py script running, install the Python gearman module yourself.

Then go to the PHP section to test the code first:

<?php require_once ' phpasyncclient.php ';  Date_default_timezone_set (' Asia/shanghai ');      Class Asynctest {Const Log_file = '/debug.log '; static public Function run () {if (Phpasyncclient::in_callback (__file__)) {self::log (' php Async callb             Ack ');             Phpasyncclient::p arse ();         Return             } if (Phpasyncclient::is_main (__file__)) {Self::log (' main run ');             $async _call = Phpasyncclient::getinstance ();  $async _call->asynccall (' asynctest ', ' callback ', Array (' content ' = ' Hello world!!! ',), Array (' class ' = ' asynctest ', ' method ' = ' callback ', ' params ' =&G T             Array (' content ' = ' Hello callback! ',), __file__);         Return         }} static Public function callback ($args) {self::log (' Asynctest callback Run '); Self::lOG (' asynctest callback args: '. Print_r ($args, true));         The static public function log ($content) {$fullname = DirName (__file__). Self::log_file; $content = Date (' [y-m-d h:i:s] '). $content. "         \ n ";     File_put_contents ($fullname, $content, file_append); }} asynctest::run ();

There are 3 static methods, one is the log method for debugging, and the others are literal. This example is an initial impression of this invocation. Then directly on the PHP all source code:

Php_async.zip

Then there should be a lot of people will say, win under the installation of Gearman ... So I put the Java version of the Gearman server also put up.

Java-gearman-service-0.6.6.zip

5. Conclusion

After the rhino-like size of the above configuration of the guy (to install a gearman, but also run a py script), we basically make PHP has an asynchronous call function, of course, there is a state to maintain the God horse to achieve their own. So I found that this plan is not how, too complex. It is better to use some Web service to do the Web callback (the problem is that Web callback will time out ...). ), please note the follow-up.

  • Related Article

    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.