In this article, i will introduce you howto use gearman with php.Firstly, lets have a look at the term Gearman.
Gearman provides a generic application framework to farm out work to other machines or processes that are better suited to do the work. It allows you to do work in parallel, to load balance processing, and to call functions between languages. It can be used in a variety of applications, from high-availability web sites to the transport of database replication events. In other words, it is the nervous system for how distributed processing communicates.
-Gearman official description
Let’s say that, you have some jobs and it takes a bit long, but you don’t want to wait for ending of each job. In this case, you may want to send your job a system and you can cotinue your own work as usual.Let me give an example;
User uploads a photo, and eight type of this photo(thumbnail, large image, small ,mage, etc…) is created and put these photos in user’s album.While creating these images, you can get bad gateway error due to long response time.In order to prevent bad gateway error, you can send image creating job to Gearman and response user as “Your images is being created”. With this, user doesn’t have to wait response until images completely created.
For latest release, you can visit this page.
In order to continue installation, you should install some dependency packages, Boost headers, uuid-dev and libevent.You can download by,
sudo apt-get install libboost-program-options-dev libevent-dev uuid-dev
After header installation,
tar xzf gearmand-0.24.tar.gz
If you don’t want to do those stuffs, you can install gearman by typing,
sudo apt-get install gearman-job-server
Now, gearman job server is ready and waiting for incoming requests.In command line, type
and you will get such a response
INFO Starting up
INFO Listening on 0.0.0.0:4730 (6)
INFO Creating wakeup pipe
INFO Creating IO thread wakeup pipe
INFO Adding event for listening socket (6)
INFO Adding event for wakeup pipe
INFO Entering main event loop
In order to use gearman functionalities in php, we have to install gearman library for php
sudo pecl install gearman-0.8.0
After libgearman installation you need to add “extension=gearman.so” in to php.ini.Let’s code some php!
<! — ?php $worker= new GearmanWorker(); $worker — ->addServer();
<! — ?php $client= new GearmanClient(); $client — ->addServer();
print $client->do(“reverse”, “Hello World!”);
and in other terminal run
and you will get
As you can see, client sends a job to worker, and worker reverses client’s input.Communication between client and worker is done by gearman.
I hope you got some opinion about php and gearman interaction end of this article.If you have any question, please do not hesitate to ask here.See you in next article…