Home Backend Development PHP Tutorial Research on the implementation of asynchronous operations in PHP Ancient poems about spring Quotes about reading Handwritten notes about reading

Research on the implementation of asynchronous operations in PHP Ancient poems about spring Quotes about reading Handwritten notes about reading

Jul 29, 2016 am 08:50 AM
php about

1. Why does PHP need asynchronous operations?

Generally speaking, PHP is suitable for short-term tasks such as web page display. If you perform time-consuming operations such as resizing images, importing big data, sending EDM, SMS in batches, etc., it is easy for operation timeouts to occur. . You can say that I can set an infinite timeout, etc. You also need to know that PHP has a working mode which is fastcgi. PHP does not timeout indefinitely, which does not mean that fastcgi will not timeout... If you still want fastcgi to never timeout, I It is recommended that you discuss it with your operation and maintenance personnel...

At this time, the asynchronous operation comes into play. Since it is a non-blocking operation, the operation will return immediately, and then work slowly in the background. It doesn’t matter whether it times out or not, I’m not working under the current process/thread. Look, isn't it wonderful, but actually it's also a pitfall...

2. Can PHP implement asynchronous operations?

The answer is yes, but various pure PHP implementations on the Internet are a bit awkward. Socket mode, suspended process mode, and some even directly fork the process. Very good, all kinds of gods show their magical powers. If the operation and maintenance personnel see it, they will definitely ××××× you. It would be strange if the web server is not killed...

Is there any other better way to achieve this asynchronous operation? Yes, now we only have to think about how to enable plug-ins. Check the mainstream plug-in solutions of PECL. There are a bunch of ××MQ (message queue). Among them, there is a plug-in for task distribution that comes into our sight. Gearman (actually this guy is the corner, I won’t introduce it in detail, click to connect See introduction).

3. Why choose Gearman?

If nothing else, just say that it has many clients and supports clients in many languages. You can use most of your favorite languages ​​to write workers. Personally, I am very annoyed by the language debate. You can use Shenma to write workers as you like. There is data persistence support (that is, the queue is saved to the database medium, so failure recovery is easy), and there is cluster support (in fact, many ××MQ have these functions). There are extensions on PECL, and there are also extensions implemented in pure PHP. Anyway, this Gearman has lived for a long time, and all the miscellaneous problems have been basically solved.

4. Basic idea

With the Gearman plug-in, it is much simpler. It means sending a task to gearman, sending out the executed task, and then waiting for the worker to call the PHP cli to run our php code.

I just wrote a python worker (don’t ask me why I use python, 1. I know python, 2. I don’t need to install runtime under Linux). You can write a PHP worker based on your own ideas, but well, I I don’t really trust workers running PHP. For other languages, you can try implementing a worker using java, node.js or other languages. Friends who are interested in writing workers in Golang can contact me.

phpasync_worker_py

Sorry, there are no comments in it. A configuration file and a py script. The basic function is to analyze the calling parameters and then call the PHP Cli, that's it. To make the py script run, please install the python gearman module yourself.

Then go to the PHP part and start the test code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<ol>

<li><span><span><?php  </span></span></li><li><span>require_once</span><span> </span><span>'PHPAsyncClient.php'</span><span>;  </span></li><li><span>date_default_timezone_set(</span><span>'Asia/Shanghai'</span><span>);  </span></li><li><span> </span></li><li><span>class</span><span> AsyncTest {  </span></li><li><span> </span></li><li><span>    </span><span>const</span><span> </span></li><li><span>        LOG_FILE = </span><span>'/debug.log'</span><span>;  </span></li><li><span> </span></li><li><span>    </span><span>static</span><span> </span><span>public</span><span> </span><span>function</span><span> run() {  </span></li><li><span>        </span><span>if</span><span> (PHPAsyncClient::in_callback(</span><span>__FILE__</span><span>)) {  </span></li><li><span>            self::log(</span><span>'php Async callback'</span><span>);  </span></li><li><span>            PHPAsyncClient::parse();  </span></li><li><span>            </span><span>return</span><span>;  </span></li><li><span>        }  </span></li><li><span>        </span><span>if</span><span> (PHPAsyncClient::is_main(</span><span>__FILE__</span><span>)) {  </span></li><li><span>            self::log(</span><span>'main run'</span><span>);  </span></li><li><span>            </span><span>$async_call</span><span> = PHPAsyncClient::getInstance();  </span></li><li><span>            </span><span>$async_call</span><span>->AsyncCall(</span><span>'AsyncTest'</span><span>, </span><span>'callback'</span><span>, </span><span>array</span><span>(  </span></span></li>

<li>

<span>                </span><span>'content'</span><span> => </span><span>'Hello World!!!'</span><span>,  </span>

</li>

<li>

<span>            ), </span><span>array</span><span>(  </span>

</li>

<li>

<span>                </span><span>'class'</span><span> => </span><span>'AsyncTest'</span><span>,  </span>

</li>

<li>

<span>                </span><span>'method'</span><span> => </span><span>'callback'</span><span>,  </span>

</li>

<li>

<span>                </span><span>'params'</span><span> => </span><span>array</span><span>(  </span>

</li>

<li>

<span>                    </span><span>'content'</span><span> => </span><span>'Hello Callback!'</span><span>,  </span>

</li>

<li><span>                ),  </span></li>

<li>

<span>            ), </span><span>__FILE__</span><span>);  </span>

</li>

<li>

<span>            </span><span>return</span><span>;  </span>

</li>

<li><span>        }  </span></li>

<li><span>    }  </span></li>

<li><span> </span></li>

<li>

<span>    </span><span>static</span><span> </span><span>public</span><span> </span><span>function</span><span> callback(</span><span>$args</span><span>) {  </span>

</li>

<li>

<span>        self::log(</span><span>'AsyncTest callback run'</span><span>);  </span>

</li>

<li>

<span>        self::log(</span><span>'AsyncTest callback args:'</span><span>.print_r(</span><span>$args</span><span>, true));  </span>

</li>

<li><span>    }  </span></li>

<li><span> </span></li>

<li>

<span>    </span><span>static</span><span> </span><span>public</span><span> </span><span>function</span><span> log(</span><span>$content</span><span>) {  </span>

</li>

<li>

<span>        </span><span>$fullname</span><span> = dirname(</span><span>__FILE__</span><span>).self::LOG_FILE;  </span>

</li>

<li>

<span>        </span><span>$content</span><span> = </span><span>date</span><span>(</span><span>'[Y-m-d H:i:s]'</span><span>).</span><span>$content</span><span>.</span><span>"\n"</span><span>;  </span>

</li>

<li>

<span>        </span><span>file_put_contents</span><span>(</span><span>$fullname</span><span>, </span><span>$content</span><span>, FILE_APPEND);  </span>

</li>

<li><span>    }  </span></li>

<li><span>}  </span></li>

<li><span> </span></li>

<li><span>AsyncTest::run(); </span></li>

</ol>

Copy after login

There are only 3 static methods, one is the log method for debugging, and the others are literal. This example is a preliminary impression of this calling method. Then directly upload all the source code of PHP:

php_async.zip

Then there should be many people saying that gearman cannot be installed under win... So I will also put the java version of gearman server.

java-gearman-service-0.6.6.zip

5. Conclusion

After configuring a thing as big as a rhinoceros (to install a Gearman and run a Py script), we basically made PHP own In addition to the asynchronous calling function, of course there is also a state maintenance function that needs to be implemented by yourself. So I found that this solution is actually not good and too complicated. It would be better to use some web service methods to make web callbacks (the problem is that web callbacks will also time out...), please pay attention to the follow-up.

Original link: http://my.oschina.net/wakanoc/blog/101789

The above introduces the research on the implementation of asynchronous operations in PHP, including PHP, and related aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

See all articles