PHP并发多进程处理利器Gearman使用介绍,利器gearman
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其中的一个,相当与一个并发的分发任务处理的例子
<?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);
gearman_work.php
<?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());
我在3个终端中都执行了gearman_work.php
ryan@ryan-lamp:~$ ps aux | grep gearman* | grep -v grep gearman 1504 0.0 0.1 60536 1264 ? 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
来查看下执行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这个工具.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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,

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!

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

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!

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