Using Gearman with PHP: Setup, Worker and Client Scripts, and Deployment
This article provides a step‑by‑step guide for configuring Gearman persistence, writing PHP worker and client scripts, setting up GearmanManager, launching the gearmand server with MySQL storage, and running the client to dispatch thousands of email jobs, illustrating fault‑tolerant asynchronous processing.
Preparation : To avoid downtime during business processing, configure Gearman's persistence method and use GearmanManager to manage worker scripts for easier testing.
Write the worker script (sendEmail.php) :
<code><?php
// Note: function name matches file name
function sendEmail($job) {
$workId = uniqid();
// workload() gets the serialized data from the client
$data = json_decode($job->workload(), true);
// Simulate processing (e.g., sending an email)
sleep(1);
echo "workId: {$workId} 发送 {$data['email']} 成功\n";
}
</code>Write the client script (client.php) :
<code><?php
// Create a client
$client = new GearmanClient();
// Add a job server
$client->addServer('127.0.0.1', 4730);
$cnt = 5000;
$ret = array();
// Loop to send 5000 email jobs
for ($i = 0; $i < $cnt; ++$i) {
// doBackground is asynchronous and returns a handle
$ret[$i] = $client->doBackground('sendEmail', json_encode(array(
'email' => "{$i}@qq.com",
'title' => "邮件标题{$i}",
'body' => "我是内容{$i}"
)));
}
</code>Configure GearmanManager : Edit /data/GearmanManager/etc/GearmanManager.ini and add the following section to start five dedicated processes for the sendEmail job.
<code>[sendEmail]
; specify 5 processes
dedicated_count=5
; only run sendEmail jobs
dedicated_only=1
</code>Start the gearmand server with MySQL persistence:
<code>gearmand -d -q mysql \
--mysql-host=192.168.1.100 \
--mysql-port=3306 \
--mysql-user=gearman \
--mysql-password=123456 \
--mysql-db=gearman \
--mysql-table=gearman_queue &
</code>Launch GearmanManager :
<code>cd /data/GearmanManager
./bin/pecl_manager.php -c /data/GearmanManager/etc/GearmanManager.ini -vvv
</code>Run the client to dispatch the jobs:
<code>/data/php56/bin/php /data/client.php
</code>When the manager is stopped with Ctrl+C , the workers are killed but the client continues to send requests; the job data remains stored in MySQL. Restarting the workers causes Gearman to reload and process the pending jobs.
Note: If Gearman cannot connect to MySQL on a Windows host, temporarily disable the Windows 10 firewall and enable ICMP echo replies.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.