SlideShare a Scribd company logo
Gearman work queue in php
用 Gearman 打造 PHP 排程
2013.10.05
@appleboy
2
Who am I
Bo-Yi Wu @appleboy
http://blog.wu-boy.com
https://github.com/appleboy
任職於瑞昱半導體 RealTek(IC Design House)
3
今日來聊聊排程系統
4
排程使用時機 ?
5
不需要即時回覆
都可以使用排程
6
哪些應用需要排程 ?
7
使用者註冊系統
8
使用者註冊
填寫表單完成
寄發認證信
使用者收到回覆
未使用排程
處理資料
透過第三方寄信
Amazone SES
9
缺點 Response time 過長
使用者不需要等伺服器寄信
( 來自知名插畫家彎彎 )
10
使用者註冊
填寫表單完成
寄發認證信
使用者收到回覆
使用排程
處理資料
寫入排程
11
Email Queue?
Github Social Coding
12
Application Server
Database Database Database
Work Queue
13
執行排程
Linux crontab
Ref: http://www.xenstreet.com/2013/03/choosing-the-right-linux/
14
<?php
$link = mysqli_connect("host", "user", "passw", "db");
$query = 'SELECT * FROM jobs where status = "on"';
$result = $link->query($query);
while($row = mysqli_fecth_array($result)) {
// …....
// do work
// …....
$sql = 'update jobs set status = "off" where id = {$row["id"]}';
$link->query($sql);
}
15
每分鐘執行一次
*/1 * * * * root cron.sh
16
優點
●
容易瞭解
●
任何程式語言都可以實現
●
快速 Deploy 到任何機器
17
缺點
●
每分鐘只能執行一次
●
Race condition
●
浪費 Database 資源
18
換個寫法來試試看
19
每 10 秒執行一次
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
$query = 'SELECT * FROM jobs where status = "on"';
$done = false;
while(!$done) {
$result = $link->query($query);
if ($result->num_rows > 0) {
// do work
$sql = 'update jobs set status = "off" where id = {$row["id"]}';
$link->query($sql);
} else {
sleep(10);
}
}
20
缺點
●
真的 10 秒執行一次 ?
●
Race condition
●
更浪費 Database 資源
21
如果沒有 Race Condition
22
#!/bin/sh
(sleep 5 && /path/script.sh) &
(sleep 15 && /path/script.sh) &
(sleep 25 && /path/script.sh) &
(sleep 35 && /path/script.sh) &
(sleep 45 && /path/script.sh) &
(sleep 55 && /path/script.sh) &
每 10 秒執行一次
23
如何分配處理這些問題 ?
24
Using Gearman
25
What is Gearman?
It allows you to do work in
parallel, to load balance
processing, and to call
functions between languages.
26
Client in
Perl,Python,PHP
Java,C#(.Net)
27
even
MySQL,PostgreSQL
28
How Does Gearman Work?
29
Gearman 優點
30
Work Queues
●
淺顯易懂
Got job do job repeat→ →
Application
Gearmand
Worker
Got job
Do job
31
Work Queues
●
淺顯易懂
Get job do job repeat→ →
●
跨語言
任何平台只要能存入字串即可
32
Multiple Language
Application
Gearmand
Application
Worker Worker
33
Work Queues
●
淺顯易懂
Get job do job repeat→ →
●
跨語言
任何平台只要能存入字串即可
●
跨平台
當 Client 寫入工作時, Worker 不需要啟動
34
跨平台
Application
Gearmand
Application
Gearmand
35
Work Queues
●
淺顯易懂
Get job do job repeat→ →
●
跨語言
任何平台只要能存入字串即可
●
跨平台
當 Client 寫入工作時, Worker 不需要啟動
●
即時性
可以為同步或非同步
36
Gearman Architecture
佈署架構
37
Application
Gearmand
Job
38
Application
Gearmand
Job
Worker
Job
39
Application
Gearmand
Job
Worker
Job Response
40
Application
Gearmand
Job
Worker
Job Response
Response
41
Application
Gearmand
Worker
Worker
Worker
42
Application
Gearmand
Worker
Worker
Gearmand
43
Application
Gearmand
Worker
Worker
Gearmand
Application
44
結論 :Gearman 擴充性佳
45
不論要幾台 gearmand
跟數個 worker 都可以
46
Application 只會跟
Gearmand 溝通
47
多個 Application 不管
丟出多少個 Jobs
48
最終由多個 Job Server
分配工作
49
Synchronous
vs
Asynchronous
50
Synchronous
Application
Gearmand
Job
Worker
Job Response
Response
51
Asynchronous
Application
Gearmand
Job
Worker
Job Done!
52
Installation
安裝方式
53
Installation
●
Job Server (C)
●
Client library (PHP,Python ...)
●
Worker library (PHP,Python ...)
54
Job Server
安裝方式
55
Ubuntu/Debian
aptitude -y install gearman gearman-job-server libgearman-dev libdrizzle0
56
CentOS/Fedora
yum -y install libgearman gearmand libgearman-devel libdrizzle
57
Tarball install
https://gist.github.com/appleboy/6774735
58
Gearmand enabled using
MySQL(Mariadb)
Postgresql
SQL Lite
Memcached
59
MySQL Example
/etc/default/gearman-job-server
-q mysql
--mysql-host=localhost
--mysql-user=xx
--mysql-password=xx
--mysql-db=ovoq
--mysql-table=gearman_queue
60
Client Library
pecl install channel://pecl.php.net/gearman-1.1.2
echo 'extension=gearman.so' > /path/gearman.ini
61
Quick Test
php -i | grep 'gearman'
62
Gearman in PHP Client
63
PHP Client
# Create a client object
$gm = new GearmanClient();
# Add default server, default is localhost:4730
$gm->addServer();
# Do Job
$result = $gm->doNormal("reverse", "Hello!");
echo "Success: $resultn";
64
Do background Job
$job = $gm->doBackground("reverse", "apple");
65
Gearman in PHP Worker
66
PHP Worker
# Define worker job function
function reverse_fn($job) { //.... }
# fetch message from client
function reverse_fn($job) {
$data = $job->workload();
}
67
PHP Worker
# Create our worker object.
$gm= new GearmanWorker();
# Add default server (localhost).
$gm->addServer();
# Register function "reverse"
$gm->addFunction("reverse", "reverse_fn");
# Waiting for job...
while($gm->work());
68
Multiple Jobs
$gm->addFunction("reverse", "reverse_fn");
$gm->addFunction("resize", "resize_fn");
$gm->addFunction("queue", "queue_fn");
…...
69
Anonymous function
$gm->addFunction("reverse", function($job){
$data = $job->workload();
});
70
Gearman in CodeIgniter
71
CodeIgniter Gearman Library
https://github.com/appleboy/CodeIgniter-Gearman-Library
72
Installation via Spark
php tools/spark install -v1.0.1 codeigniter-gearman
73
Setup Gearmand Server and Port
config/gearman.php
$config['gearman_server'] = array('localhost');
$config['gearman_port'] = array('4730');
74
CodeIgniter Client
75
Implement Image Resize Job
create app controller
76
class App extends CI_Controller
{
public function resize_sync()
public function resize_async()
}
77
public function resize_sync()
{
$data = json_encode(array('file_name' => 'test.png'));
$client = $this->lib_gearman->gearman_client();
do {
$this->lib_gearman->do_job_foreground('resize', $data);
switch($client->returnCode()) { //.... }
} while ($client->returnCode() != GREARMAN_SUCCESS);
}
78
class App extends CI_Controller
{
public function resize_sync()
public function resize_async()
}
79
public function resize_async()
{
$data = json_encode(array('file_name' => 'test.png'));
$client = $this->lib_gearman->gearman_client();
$this->lib_gearman->do_job_background('resize', $data));
}
80
CodeIgniter Worker
create cli controller
81
class Cli extends CI_Controller
{
public static function image_resize()
public static function email_queue()
public function worker()
}
82
public static function image_resize($job)
{
$data = json_decode($job->workload(), true);
$ci =& get_instance();
$ci->image_lib->initialize($config);
$ci->image_lib->resize();
$ci->image_lib->clear();
}
83
Define Worker
84
public function worker()
{
$worker = $this->lib_gearman->gearman_worker();
$this->lib_gearman
->add_worker_function('resize', 'Cli::image_resize');
$this->lib_gearman
->add_worker_function('queue', 'Cli::email_queue');
while ($this->lib_gearman->work());
}
85
Start Worker
$ php index.php cli worker
86
Running workers via script
#!/bin/sh
script="index.php cli worker"
folder="/script_path/"
max_worker="5"
php_bin="/usr/bin/php"
count=0
current_count=$(ps aux | grep "index.php cli worker" | grep -v "grep" | wc -l)
if test $current_count -lt $max_worker
then
cd $folder
$php_bin $folder$script &
else
echo "The worker count has been limited."
fi
https://gist.github.com/appleboy/6806323
87
About Job Data
Don't pass 2GB object.
Gearman is not data center.
88
Keep your message data small
Amazone SQS message siez: 256K
http://goo.gl/0MBq8W
89
Scalability
90
Client Client
Job Server
Client
ClientWorker Worker Worker Worker
Job Server
Client
91
you can scale out your
clients and workers
as needed
92
Client Setting
Client1, Client2: Gearman1
Client3, Client4: Gearman2
…...
93
Worker Setting
Worker[1-4]:Server[1-2]
…...
94
Add new Job Server...
95
Reconfigure all setting
(client and worker program)
96
Reconfigure all setting
(client and worker program)
even
Deploy Tool
97
如何控制易怒的情緒?
98
How to improve your
architecture?
99
Client Client
Job Server
Client
ClientWorker Worker Worker Worker
Job Server
Client
Proxy (Haproxy ...)
100
Live Demo
Email Queue.
101
Any Questions?
102
Thanks
全體工作人員和聽眾

More Related Content

PDF
How to integrate front end tool via gruntjs
PPTX
PHP & JavaScript & CSS Coding style
PDF
Introduction to Grunt.js on Taiwan JavaScript Conference
PPTX
Deployment Patterns in the Ruby on Rails World
PDF
GraphQL IN Golang
PDF
Drone CI/CD Platform
KEY
Crafting Beautiful CLI Applications in Ruby
PDF
Drone CI/CD 自動化測試及部署
How to integrate front end tool via gruntjs
PHP & JavaScript & CSS Coding style
Introduction to Grunt.js on Taiwan JavaScript Conference
Deployment Patterns in the Ruby on Rails World
GraphQL IN Golang
Drone CI/CD Platform
Crafting Beautiful CLI Applications in Ruby
Drone CI/CD 自動化測試及部署

What's hot (20)

PDF
Drone 1.0 Feature
PDF
One commit, one release. Continuously delivering a Symfony project.
PDF
Continous Delivering a PHP application
PDF
JCConf 2015 workshop 動手玩 Java 專案建置工具
PDF
Rest, sockets em golang
PDF
Build microservice with gRPC in golang
PDF
Automate Your Automation | DrupalCon Vienna
KEY
Ruby and Rails Packaging to Production
ODP
Vagrant move over, here is Docker
PDF
Использование Docker в CI / Александр Акбашев (HERE Technologies)
PDF
Lviv 2013 d7 vs d8
PDF
Development Principles & Philosophy
PDF
Drupal contrib module maintaining
PDF
Laravel 4 package development
PDF
[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...
PDF
Zend Framework 1.8 workshop
PDF
Deploying 3 times a day without a downtime @ Rocket Tech Summit in Berlin
PDF
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
PDF
React Native in Production
PDF
Gradle in 45min
Drone 1.0 Feature
One commit, one release. Continuously delivering a Symfony project.
Continous Delivering a PHP application
JCConf 2015 workshop 動手玩 Java 專案建置工具
Rest, sockets em golang
Build microservice with gRPC in golang
Automate Your Automation | DrupalCon Vienna
Ruby and Rails Packaging to Production
Vagrant move over, here is Docker
Использование Docker в CI / Александр Акбашев (HERE Technologies)
Lviv 2013 d7 vs d8
Development Principles & Philosophy
Drupal contrib module maintaining
Laravel 4 package development
[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...
Zend Framework 1.8 workshop
Deploying 3 times a day without a downtime @ Rocket Tech Summit in Berlin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
React Native in Production
Gradle in 45min
Ad

Viewers also liked (20)

PPTX
Git flow 與團隊合作
PPTX
Why to choose laravel framework
PPTX
用 Docker 改善團隊合作模式
PPTX
Write microservice in golang
PDF
advanced introduction to codeigniter
PPTX
Git Flow and JavaScript Coding Style
PDF
Phpconf 2011 introduction_to_codeigniter
PDF
Introduction to MVC of CodeIgniter 2.1.x
PDF
Introduction to git
PPTX
How to choose web framework
PDF
2014 OSDC Talk: Introduction to Percona XtraDB Cluster and HAProxy
PDF
You must know about CodeIgniter Popular Library
PDF
RESTful API Design & Implementation with CodeIgniter PHP Framework
PPTX
Docker 基礎介紹與實戰
PDF
Automating your workflow with Gulp.js
PDF
Maintainable PHP Source Code
ODP
Magento phpconf 2013
KEY
Gearman Introduction
PDF
MapReduce Using Perl and Gearman
PDF
Gearman For Beginners
Git flow 與團隊合作
Why to choose laravel framework
用 Docker 改善團隊合作模式
Write microservice in golang
advanced introduction to codeigniter
Git Flow and JavaScript Coding Style
Phpconf 2011 introduction_to_codeigniter
Introduction to MVC of CodeIgniter 2.1.x
Introduction to git
How to choose web framework
2014 OSDC Talk: Introduction to Percona XtraDB Cluster and HAProxy
You must know about CodeIgniter Popular Library
RESTful API Design & Implementation with CodeIgniter PHP Framework
Docker 基礎介紹與實戰
Automating your workflow with Gulp.js
Maintainable PHP Source Code
Magento phpconf 2013
Gearman Introduction
MapReduce Using Perl and Gearman
Gearman For Beginners
Ad

Similar to Gearman work queue in php (20)

PPT
Gearmanpresentation 110308165409-phpapp01
PPTX
Distributed Applications with Perl & Gearman
PPTX
轉轉轉好運旺來一起來之雲端轉檔大作戰!
PDF
Cross-Platform App Development with Flutter, Xamarin, React Native
PDF
Batteries not included
PDF
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
PDF
Google Back To Front: From Gears to App Engine and Beyond
PDF
Kogito: cloud native business automation
PPT
Scripting Oracle Develop 2007
PPTX
soscon2018 - Tracing for fun and profit
PDF
Pyramid Deployment and Maintenance
PDF
Gain more freedom when migrating from Camunda 7 to 8.pdf
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
PDF
Tasks: you gotta know how to run them
PPTX
Js tacktalk team dev js testing performance
PDF
Serverless and you @ Women Who Code London 2020
ODP
Pyramid deployment
PDF
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
PDF
Distributed Queue System using Gearman
PDF
Grails 101
Gearmanpresentation 110308165409-phpapp01
Distributed Applications with Perl & Gearman
轉轉轉好運旺來一起來之雲端轉檔大作戰!
Cross-Platform App Development with Flutter, Xamarin, React Native
Batteries not included
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Google Back To Front: From Gears to App Engine and Beyond
Kogito: cloud native business automation
Scripting Oracle Develop 2007
soscon2018 - Tracing for fun and profit
Pyramid Deployment and Maintenance
Gain more freedom when migrating from Camunda 7 to 8.pdf
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Tasks: you gotta know how to run them
Js tacktalk team dev js testing performance
Serverless and you @ Women Who Code London 2020
Pyramid deployment
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Distributed Queue System using Gearman
Grails 101

More from Bo-Yi Wu (14)

PDF
用 Go 語言打造多台機器 Scale 架構
PDF
Job Queue in Golang
PDF
Golang Project Layout and Practice
PDF
Introduction to GitHub Actions
PPTX
Go 語言基礎簡介
PPTX
drone continuous Integration
PPTX
Gorush: A push notification server written in Go
PPTX
用 Drone 打造 輕量級容器持續交付平台
PPTX
用 Go 語言 打造微服務架構
PPTX
Introduction to Gitea with Drone
PDF
運用 Docker 整合 Laravel 提升團隊開發效率
PDF
用 Go 語言實戰 Push Notification 服務
PPTX
用 Go 語言打造 DevOps Bot
PPTX
A painless self-hosted Git service: Gitea
用 Go 語言打造多台機器 Scale 架構
Job Queue in Golang
Golang Project Layout and Practice
Introduction to GitHub Actions
Go 語言基礎簡介
drone continuous Integration
Gorush: A push notification server written in Go
用 Drone 打造 輕量級容器持續交付平台
用 Go 語言 打造微服務架構
Introduction to Gitea with Drone
運用 Docker 整合 Laravel 提升團隊開發效率
用 Go 語言實戰 Push Notification 服務
用 Go 語言打造 DevOps Bot
A painless self-hosted Git service: Gitea

Recently uploaded (20)

PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PDF
Smarter Business Operations Powered by IoT Remote Monitoring
PDF
REPORT: Heating appliances market in Poland 2024
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
DevOps & Developer Experience Summer BBQ
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
This slide provides an overview Technology
PDF
Doc9.....................................
PDF
Software Development Methodologies in 2025
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Smarter Business Operations Powered by IoT Remote Monitoring
REPORT: Heating appliances market in Poland 2024
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
DevOps & Developer Experience Summer BBQ
Understanding_Digital_Forensics_Presentation.pptx
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
Dell Pro 14 Plus: Be better prepared for what’s coming
GamePlan Trading System Review: Professional Trader's Honest Take
A Day in the Life of Location Data - Turning Where into How.pdf
Chapter 2 Digital Image Fundamentals.pdf
This slide provides an overview Technology
Doc9.....................................
Software Development Methodologies in 2025
ChatGPT's Deck on The Enduring Legacy of Fax Machines
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx

Gearman work queue in php