The document discusses using queue systems to execute tasks asynchronously in the background to improve application performance and scalability. It provides an overview of different types of queue systems including dedicated job queues like Gearman and Beanstalkd, message queues like RabbitMQ, and software-as-a-service queues like Amazon SQS. It also discusses using databases like Redis as queues. The document then dives deeper into examples of using Gearman and Beanstalkd in PHP applications and compares their performance. It also discusses using queue abstraction layers and best practices for queueing jobs.
About me
•
Jurian Sluiman
•
Founder@ soflomo (Delft, The Netherlands)
•
Web development (eCommerce, health care)
•
Zend Framework 2 contributor
•
Blogger: http://juriansluiman.nl
•
Twitter: @juriansluiman
Queue systems
•
Execute tasksin background
•
Return your response fast!
request
response
Server
(Producer)
Queue
•
Producer: piece of code pushing new jobs
•
Worker:
piece of code consuming jobs
Worker
Workers
Run via ZF2app
php public/index.php queue beanstalkd default
Configuration
•
Time-out for blocking calls
•
Maximum number of cycles
•
Maximum memory usage
•
Signal handlers for SIGTERM and SIGINT
31.
Dependency injection
MyModuleJobEmail
class Emailextends AbstractJob
{
protected $transport;
public function __construct(Transport $transport)
{
$this->transport = $transport;
}
public function execute()
{
$payload = $this->getContent();
$message = new Message;
$message->setTo($payload['to']);
$message->setMessage($payload['message']);
}
}
$this->transport->send($message);
32.
Dependency injection
MyModuleFactoryEmailJobFactory
use MyModuleJobEmailas EmailJob;
class EmailJobFactory implements FactoryInterface
{
public function createService(ServiceLocator $sl)
{
$transport = $sl->get('MyEmailTransport');
return new EmailJob($transport);
}
}
module.config.php
'slm_queue' => [
'job_manager' => [
'MyEmailJob' => 'MyModuleFactoryEmailJobFactory'
]
]
Queue aware jobs
MyModuleJobFoo
classFoo extends AbstractJob implements QueueAwareInterface
{
use QueueAwareTrait;
public function execute()
{
// work here
}
}
$job = new BarJob();
$this->getQueue()->push($job);
Jobs in services
MyModuleServiceFoo
classFoo
{
protected $queue;
public function __construct(QueueInterface $queue)
{
$this->queue = $queue;
}
public function doSomething()
{
// work here
$job = new BarJob;
$this->queue->push($job);
}
}
38.
Lazy services
class Buzzer
{
publicfunction __construct()
{
sleep(5);
}
}
public function buzz()
{
// do something
}
Lazy services with a Proxy pattern by Marco Pivetta (Ocramius)
39.
Lazy services
class BuzzerProxyextends Buzzer
{
private $sl;
private $instance;
public function __construct(ServiceLocator $sl)
{
$this->sl = $sl;
}
private function initialize()
{
$this->initialized = true;
$this->original = $this->sl->get('Buzzer');
}
}
public function buzz()
{
if (!$this->initialized) { $this->initialize(); }
return $this->instance->buzz();
}