Table of Contents
PHP并发多进程处理利器Gearman使用介绍,利器gearman
Home php教程 php手册 PHP并发多进程处理利器Gearman使用介绍,利器gearman

PHP并发多进程处理利器Gearman使用介绍,利器gearman

Jun 13, 2016 am 08:39 AM
gearman php concurrency multi-Progress

PHP并发多进程处理利器Gearman使用介绍,利器gearman

工作中我们有时候会遇到比如需要同时发布数据到多个个服务器上,或者同时处理多个任务。可以使用PHP的curl_multi的方式并发处理请求,但是由于网络和数据以及各个服务器等等的一些情况导致这种并发处理的响应时间很慢,因为在并发请求的过程中还包括记录日志,处理数据等逻辑,等待处理结果并返回,所以也不能友好的满足后台操作的体验。

现在有另外一种方案,利Gearman来实现并发的需求。通过Client将请求发送到Gearman的Jobs,在每个Work中来再来进行curl_multi和数据处理和日志等一些操作,同时用supervisor 来监控Gearman以及Works的进程,这样可以实现一个并行的多进程和负载均衡的方案。

Gearman可以做什么:

异步处理:图片处理,订单处理,批量邮件/通知之类的
要求高CPU或内存的处理:大容量的数据处理,MapReduce运算,日志聚集,视频编码
分布式和并行的处理
定时处理:增量更新,数据复制
限制速率的FIFO处理
分布式的系统监控任务

Gearman工作原理:
使用Gearman的应用通常有三部分组成:一个Client、一个Worker、一个 任务服务器。 Client的作用是提出一个 Job 任务 交给 Job Server 任务服务器。Job Server 会去寻找一个 合适的 Worker 来完成这项任务。Worker 执行由 Client 发送过来的 Job,并且将结果通过 Job Server 返回给 Client。Gearman 提供了 Client 和 Worker 的 API,利用这些API 应用可以同 Gearman Job Server来进行通信。Gearman 内部 Client 和 Worker 之间的通信都是通过 TCP 连接来进行的。

Gearman可以将工作的负载分担到不同的机器中。

安装:

复制代码 代码如下:
rpm -ivh http://dl.iuscommunity.org/pub/ius/stable/Redhat/6/x86_64/epel-release-6-5.noarch.rpm
yum install -y gearmand

启动:
gearmand -d

安装PHP Gearman扩展
我都是用pcel来安装的,你也可以下载源码包来编译安装,但是记得要先安装libgearman和re2c,不然扩展编译安装会出错。

pecl install gearman #不成功并提示版本问题可以试试 pecl install gearman-1.0.3,默认好像是1.1.2
编译安装也很简单
复制代码 代码如下:
wget -c http://pecl.php.net/get/gearman-1.1.1.tgz
tar zxvf gearman-1.1.1.tgz
phpize
./configure
make && make install
echo "extension=gearman.so" >> /etc/php.ini

PHP接口函数
Gearman提供很多完善的扩展函数,包括GearmanClient,GearmanJob,GearmanTask,GearmanWorker,具体可以查看PHP官方手册.
这是官方提供的Example其中的一个,相当与一个并发的分发任务处理的例子

<&#63;php

$client = new GearmanClient();
$client->addServer();

// initialize the results of our 3 "query results" here
$userInfo = $friends = $posts = null;

// This sets up what gearman will callback to as tasks are returned to us.
// The $context helps us know which function is being returned so we can
// handle it correctly.
$client->setCompleteCallback(function(GearmanTask $task, $context) use (&$userInfo, &$friends, &$posts) {
switch ($context)
{
case 'lookup_user':
$userInfo = $task->data();
break;
case 'baconate':
$friends = $task->data();
break;
case 'get_latest_posts_by':
$posts = $task->data();
break;
}
});

// Here we queue up multiple tasks to be execute in *as much* parallelism as gearmand can give us
$client->addTask('lookup_user', 'joe@joe.com', 'lookup_user');
$client->addTask('baconate', 'joe@joe.com', 'baconate');
$client->addTask('get_latest_posts_by', 'joe@joe.com', 'get_latest_posts_by');

echo "Fetching...\n";
$start = microtime(true);
$client->runTasks();
$totaltime = number_format(microtime(true) - $start, 2);

echo "Got user info in: $totaltime seconds:\n";
var_dump($userInfo, $friends, $posts);
Copy after login

gearman_work.php

<&#63;php

$worker = new GearmanWorker();
$worker->addServer();

$worker->addFunction('lookup_user', function(GearmanJob $job) {
// normally you'd so some very safe type checking and query binding to a database here.
// ...and we're gonna fake that.
sleep(3);
return 'The user requested (' . $job->workload() . ') is 7 feet tall and awesome';
});

$worker->addFunction('baconate', function(GearmanJob $job) {
sleep(3);
return 'The user (' . $job->workload() . ') is 1 degree away from Kevin Bacon';
});

$worker->addFunction('get_latest_posts_by', function(GearmanJob $job) {
sleep(3);
return 'The user (' . $job->workload() . ') has no posts, sorry!';
});

while ($worker->work());
Copy after login

我在3个终端中都执行了gearman_work.php

ryan@ryan-lamp:~$ ps aux | grep gearman* | grep -v grep
gearman 1504 0.0 0.1 60536 1264 &#63; Ssl 11:06 0:00 /usr/sbin/gearmand --pid-file=/var/run/gearman/gearmand.pid --user=gearman --daemon --log-file=/var/log/gearman-job-server/gearman.log --listen=127.0.0.1
ryan 2992 0.0 0.8 43340 9036 pts/0 S+ 14:05 0:00 php /var/www/gearmand_work.php
ryan 3713 0.0 0.8 43340 9036 pts/1 S+ 14:05 0:00 php /var/www/gearmand_work.php
ryan 3715 0.0 0.8 43340 9036 pts/2 S+ 14:05 0:00 php /var/www/gearmand_work.php
Copy after login

来查看下执行gearman_work.php的结果shell

复制代码 代码如下:
Fetching...
Got user info in: 3.03 seconds:
string(59) "The user requested (joe@joe.com) is 7 feet tall and awesome"
string(56) "The user (joe@joe.com) is 1 degree away from Kevin Bacon"
string(43) "The user (joe@joe.com) has no posts, sorry!"

看到上面的3.03 seconds,说明client请求过去的任务被并行分发执行了。
在实际的生产环境中,为了监测gearmand和work的进程没有被意外退出,我们可以借助Supervisor这个工具.

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)

Application method of shared memory between multiple processes in Golang function Application method of shared memory between multiple processes in Golang function May 17, 2023 pm 12:52 PM

As a highly concurrent programming language, Golang's built-in coroutine mechanism and multi-threaded operations enable lightweight multi-tasking. However, in a multi-process processing scenario, communication and shared memory between different processes have become key issues in program development. This article will introduce the application method of realizing shared memory between multiple processes in Golang. 1. How to implement multi-process in Golang In Golang, multi-process concurrent processing can be implemented in a variety of ways, including fork, os.Process,

Let's talk about multi-process and multi-threading in Node.js Let's talk about multi-process and multi-threading in Node.js Jul 25, 2022 pm 07:45 PM

Everyone knows that Node.js is single-threaded, but they don’t know that it also provides a multi-thread module to speed up the processing of some special tasks. This article will lead you to understand the multi-threading of Node.js, hoping to learn more about it. Everyone helps!

Is golang multi-process? Is golang multi-process? Jul 07, 2023 am 10:18 AM

Golang is a multi-process, and its thread model is the MPG model. Overall, Go processes and kernel threads correspond to many-to-many, so first of all, they must be multi-threaded. Golang has some so-called M ratio N model. N go routines can be created under M threads. Generally speaking, N is much larger than M. It is essentially a multi-threaded model. However, the scheduling of coroutines is determined by the runtime of Go. It is emphasized that developers should Use channels for synchronization between coroutines.

Locks and synchronization in Python concurrent programming: keeping your code safe and reliable Locks and synchronization in Python concurrent programming: keeping your code safe and reliable Feb 19, 2024 pm 02:30 PM

Locks and Synchronization in Concurrent Programming In concurrent programming, multiple processes or threads run simultaneously, which can lead to resource contention and inconsistency issues. To solve these problems, locks and synchronization mechanisms are needed to coordinate access to shared resources. Concept of Lock A lock is a mechanism that allows only one thread or process to access a shared resource at a time. When one thread or process acquires a lock, other threads or processes are blocked from accessing the resource until the lock is released. Types of locks There are several types of locks in python: Mutex lock (Mutex): ensures that only one thread or process can access resources at a time. Condition variable: Allows a thread or process to wait for a certain condition and then acquire the lock. Read-write lock: allows multiple threads to read resources at the same time, but only allows one thread to write resources

PHP development tips: How to use Gearman scheduled tasks to process MySQL database PHP development tips: How to use Gearman scheduled tasks to process MySQL database Jul 01, 2023 pm 05:30 PM

PHP development skills: How to use Gearman scheduled tasks to process MySQL database Introduction: Gearman is an open source distributed task scheduling system that can be used to execute tasks in parallel and improve the system's processing capabilities. In PHP development, we often use Gearman to handle some time-consuming tasks or asynchronous tasks. This article will introduce how to use Gearman to implement scheduled tasks to handle MySQL database operations. 1. Install Gearman in the Linux system, you can

Detailed explanation of how node implements multi-process? How to deploy node project? Detailed explanation of how node implements multi-process? How to deploy node project? Aug 03, 2022 pm 08:23 PM

How to implement multi-process in node? How to deploy node project? The following article will help you master the relevant knowledge of Node.js multi-process model and project deployment. I hope it will be helpful to you!

A summary of frequently asked questions about PHP multi-process development interviews (with answers) A summary of frequently asked questions about PHP multi-process development interviews (with answers) Dec 21, 2022 pm 05:30 PM

This article brings you relevant knowledge about PHP, which mainly introduces issues related to PHP multi-process development. Here is a summary of some multi-process development issues for you, with answers. Let’s take a look at them together. I hope it will be helpful to everyone. helpful.

Golang concurrent programming skills: in-depth analysis of the multi-process model Golang concurrent programming skills: in-depth analysis of the multi-process model Feb 29, 2024 am 10:36 AM

Golang Concurrent Programming Tips: In-depth Analysis of the Multi-Process Model In the field of concurrent programming, Golang, as a powerful programming language, is favored by developers for its concise syntax and built-in concurrency support. In Golang, concurrent programming can be easily implemented using goroutine and channel, improving program performance and efficiency. However, in some specific scenarios, using the multi-process model is also an effective concurrent programming method. This article will provide an in-depth analysis of how to use Golang

See all articles