search
HomeBackend DevelopmentPHP Tutorialphp安装gearman扩展实现异步分步式任务

一、简介

Gearman是一个分发任务的程序框架,它会对作业进行排队自动分配到一系列机器上。gearman跨语言跨平台,很方便的实现异步后台任务。php官方收录:http://php.net/manual/zh/book.gearman.php


如上图,一个Gearman请求的处理过程涉及三个角色:Client -> Job -> Worker。

Client:请求的发起者,可以是C,PHP,Perl,MySQL UDF等等。
Job:请求的调度者,用来负责协调把Client发出的请求转发给合适的Work。
Worker:请求的处理者,可以是C,PHP,Perl等等。

二、安装

1、安装服务器端:

官方下载,请到https://launchpad.net/gearmand。

yum install boost-devel* gperf* libevent-devel* libuuid-devel
wget https://launchpad.net/gearmand/1.2/1.1.12/+download/gearmand-1.1.12.tar.gz
tar zxvf gearmand…
cd gearmand …
./configure
make && make install

安装该扩展需要先安装一些依赖,建议直接默认./configure,不要指定路径等。

常见问题1:提示找不到boost>=1.39,明明已经安装了,这里应该是没有安装gcc-c++,有的机器有gcc却不一定带有gcc-c++。yum install gcc-c++应该就可以了。

常见问题2:安装完成后启动不成功,gearmand -d或者gearmand -d -u root都启动不起来。gearmand -vvv调试模式却提示未定义选项-v。这时应该是触发gearmand新版本的bug了,查看log应该能看到“000000 [  main ] socket()(Address family not supported by protocol) -> libgearman-server/gearmand.cc:470”这个错误,解决办法是启动时添加参数-L 0.0.0.0,限定只绑定ipv4地址,忽略ipv6。或者安装不高于1.0.2的版本。参见官方反馈帖子:https://bugs.launchpad.net/gearmand/+bug/1134534

参考链接:http://www.usamurai.com/2013/05/01/install-gearman-from-source-in-centos/

2、安装gearman的php扩展

下载扩展程序:http://pecl.php.net/package/gearman

wget http://pecl.php.net/get/gearman-1.1.2.tgz
tar zxvf gearman-1….
cd gearman-1 …
phpize
./configure
make && make install

很快就安装完成,最后会展示so文件的路径,如: /usr/lib64/php/modules/

在php.ini末尾加上extension=”/usr/lib64/php/modules/gearman.so”,重启apache,输出php –info |grep “gearman”或者php -m或者网页输出phpinfo()都能看到已经安装成功。

常见问题:configure时如果提示找不到php-config,请指定。如–with-php-config=/usr/local/php/bin/php-config,注意要指定完整,不要只写目录。

三、实例

client:

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

$client=newGearmanClient();

$client->addServer('127.0.0.1', 4730);//本机可以直接addServer(),默认服务器端使用4730端口

$client->setCompleteCallback('completeCallBack');//先绑定才有效

 

$result1=$client->do('say','do');//do是同步进行,进行处理并返回处理结果。

$result2=$client->doBackground('say','doBackground');//异步进行,只返回处理句柄。

$result3=$client->addTask('say','addTask');//添加任务到队列,同步进行?通过添加task可以设置回调函数。

$result4=$client->addTaskBackground('say','addTaskBackground');//添加后台任务到队列,异步进行?

$client->runTasks();//运行队列中的任务,只是do系列不需要runTask()。

 

echo'result1:';

var_dump($result1);

echo'
';

 

echo'result2:';

var_dump($result2);

echo'
';

 

echo'result3:';

var_dump($result3);

echo'
';

 

echo'result4:';

var_dump($result4);

echo'
';

 

//绑定回调函数,只对addTask有效

functioncompleteCallBack($task)

{

    echo'CompleteCallback!handle result:'.$task->data().'
';

}

worker:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

$worker=newGearmanWorker();

$worker->addServer();

$worker->addFunction('say',function(GearmanJob$job){

    $workload=$job->workload();//接收client传递的数据

    echo'receive data:'.$workload.PHP_EOL;

    returnstrrev($workload);//仅作反转处理

});

 

//无际循环运行,gearman内部已有处理,不会出现占用过高死掉的情况

while($worker->work()){

    if($worker->returnCode() !== GEARMAN_SUCCESS){

        echo'error'.PHP_EOL;

    }

}

以上client输出:

CompleteCallback!handle result:ksaTdda
result1:string(2) “od”
result2:string(17) “H:iZ943bixttyZ:87″
result3:object(GearmanTask)#2 (0) { }
result4:object(GearmanTask)#3 (0) { }

worker输出:

receive data:do
receive data:doBackground
receive data:addTaskBackground
receive data:addTask

四、pcntl扩展实现粗略的多worker守护

由于worker要长驻后台时刻准备着被jobserver调用来处理job,所以worker不能死掉,网上有的解决办法是通过定时任务进行重启 worker,这应该是不错的方案。也有说进行多进程守护,但实际上php比较难实现,通过pcntl扩展是其中一种方案,主进程forck出来的子进程 来启动运行worker,相当于worker作为主进程的子进程。主进程监护着子进程,worker死掉及时启动新的一个。但如果主进程死掉呢?由于主进 程不进行什么业务处理,死掉的概率要比子进程worker死掉的概率要小不少吧。

以下示例,主进程启动5个子进程,也就是开启5个worker,并监护着它们:

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

59

60

61

declare(ticks = 1);

$num= 5;//最大子进程数

$child= 0;//当前子进程数

 

//信号处理函数

functionsig_handler($sig)

{

    global$child;

    switch($sig) {

        caseSIGCHLD:

            $child--;

            echo'SIGCHLD received! now we have '.$child.' process'.PHP_EOL;

            break;

        caseSIGINT:

            $child--;

            echo'SIGINT received! now we have '.$child.' process'.PHP_EOL;

            break;

        caseSIGTERM:

            $child--;

            echo'SIGTERM received! now we have '.$child.' process'.PHP_EOL;   

            break;

        default:

            # code...

            break;

    }

}

 

//安装信号处理器

pcntl_signal(SIGTERM,"sig_handler");//进程被kill时发出的信号

// pcntl_signal(SIGHUP,  "sig_handler");//终端关闭时发出的信号

pcntl_signal(SIGINT,"sig_handler");//中断进程信号,如Ctrl+C

pcntl_signal(SIGCHLD,"sig_handler");//进程退出信号

 

while(true)

{

    $child++;

    $parentpid=getmypid();

    $pid= pcntl_fork();//一分为二,父进程和子进程都会执行以下代码

    if($pid== -1)

    {

        exit("can not fork!");//出错

    }elseif($pid> 0){

        //父进程处理代码

        echo'I am parent.my pid is'.$pid.' and my parent pid is'.$parentpid.PHP_EOL;

        if($child>=$num)

        {

            pcntl_wait($status);//挂起,while语句不会继续执行。等待子进程结束,防止子进程成为僵尸进程

        }

    }elseif($pid== 0){

        //子进程代码

        echo'I am child, and my parent pid is '.$parentpid." my pid is ".getmypid()." now have $child process".PHP_EOL;       

        //执行具体代码

        pcntl_exec('/usr/bin/php',array('/var/www/test/mywork.php'));

 

    }

    pcntl_signal_dispatch();//分发信号,使安装的信号处理器能接收。

    //低于php5.3该函数无效,但有开头的declare (ticks = 1);表示每执行一条低级指令,

    //就检查一次信号,如果检测到注册的信号,就调用其信号处理器

    sleep(rand(3,5));//防止100%占用

}

参考链接:http://huoding.com/2012/10/30/196,http://www.zrwm.com/?cat=80

Statement
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools