Table of Contents
一、简介
二、安装
1、安装服务器端:
2、安装gearman的php扩展
三、实例
client:
worker:
四、pcntl扩展实现粗略的多worker守护
Home Backend Development PHP Tutorial php安装gearman扩展实现异步分步式任务

php安装gearman扩展实现异步分步式任务

Jun 20, 2016 pm 12:44 PM

一、简介

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 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles