Categories
PHP

Installing and Getting Started with Gearman

In my last post on Gearman, I have discussed why I love this tool. In this post, I am going to share some commands and codes to get you started with Gearman.

Install Gearman:

Install Gearman PHP Extension:

Now, let’s install gearman pecl extension:

Did that work? NO! Why? Because Gearman PECL extension is still in beta mode. Unless a PECL package is “stable”, you have to mention the full channel name to force the beta installation:

Did it work? NO! Why? It asks for “libgearman”. Hell no! I can’t find that package! 🙁

Ok, don’t panick! It happens that libgearman was initially released as libgearman1 and afterwards came libgearman2 and libgearman3.

Are you on Ubuntu? Use this:

No, I am on Debian! Okay, try this:

Still no results? Use aptitude to find libgearman.

Now run the command again:

Works, right? If you get an error message regarding “autoconf” or something, Google is your best friend. If everything is okay, go ahead!

Run Gearman Daemon:
Gearman Daemon runs in the background. It matches the client request to the specific worker process. It registers worker processes and distributes the workload among them. To run it:

If you want the daemon to go verbose and help you in debugging with detailed data, use the “-vvv” switch like this:

You can change the startup parameters by editing the file: /etc/default/gearman-job-server. Don’t forget to play with the configuration a bit 🙂

Get a PHP Worker:
Let’s code a handy string processor:

So you see, I built a super useful string processor. With it’s high level of intelligence, it can echo back the string and tell you how many characters were there. When invoked, Gearman shall call the function with the $job parameter as a gearman job. The workload() method will extract parameter passed from the client.

We just defined a function, created a GearmanWorker object, connected to the default server and registered the function.

Now, how do we invoke the job? With a client:

So, what are the output? I had three terminal tabs open. One for the main gearmand with verbose mode, another for worker.php and other one for the client output. Here’s the output sequentially:

NOTES:
— For ease of demonstration, I have executed the client from a command line script, in actual live environment, you shall be calling it from a web app.

— On a remote SSH connection, you may not be able to have 3 terminal tabs open. Put an “&” after the commands to send them to background 🙂

— Use the same command to spawn as many workers as you need

Happy Gearing with PHP!

7 replies on “Installing and Getting Started with Gearman”

If you get an error message regarding “autoconf” or something

sudo apt-get install build-essentials 🙂

Comments are closed.