Skip to content

How to write my Consumer Code

jackyhung edited this page Jun 1, 2012 · 8 revisions

Before we get to know about how to write consumer code, let's review how Consumer Dispatcher works.

Consumer code responsibility

Now you understand that Your consumer code takes the responsibility of

  • receiving the http requests from Consumer Dispatcher. usually there is a web server to handle this. like nginx, tomcat, jboss...etc.
  • handling the business logic.
  • returning ok literally as http response.

Error handling

If there is an unexpected error occurs, but you dont want to loose the job data, you should not hide this error to Consumer Dispatcher.

For example, you use your consumer code to update User table with an important data. At the moment, you loose connection to mysql, then your consumer code should return 502 http status or 'ko' as http body(with 200 status) or 'no mysql connection' as http body(with 200 status) (anything other than ok) so that Consumer Dispatcher will resend the job to your consumer code until your consumer code gets connection to mysql again and processes without any problem(it returns ok).

Example code

Many web projects stand on MVC pattern, you can use the same pattern to implement your consumers which lets you to reuse your code and infrastructure.

In job.xml , we define request-pre then we can omit the url attribute in the job definitions. Let assume in the example case, we want Consumer Dispatcher to call the same url for all jobs.

<request-pre>http://develop.youdomain.lab/consumerDispatch/</request-pre>

we encourage you to write your consumer code in this way

all requests to http://develop.youdomain.lab/consumerDispatch/ will be executed by consumerDispatchActions class, executeDispatch method.

<?php 
class consumerDispatchActions extends myActions
{
  public function executeDispatch(webRequest $request)
  {
    $queueName = $this->getRequestParameter('queueName'); //1
    $bodyData = $this->getRequestParameter('bodyData');  //2
    try
    {
      $this->callInterceptorStack('consumer_job_'.$queueName.'_stack', $bodyData); // 3
      $output = ConsumerDispatchConstant::RETURN_OK; 
    }
    catch (Exception $e)
    {
      $output = ConsumerDispatchConstant::RETURN_KO;
      errLog('{consumerDispatch}: error occured -->'.$e->getMessage());
    }

    return $this->renderText($output); //4
  }
}
?>
  1. Consumer Dispatcher sends http POST request, the queueName and bodyData are the only 2 parameters inside the request. please check consumer dispatcher http call format for more details.
  2. Same as 1.
  3. Do your business logic. You could call different business handler classes to handle logic according to the $queueName passed in.
  4. return ok if everything is fine; or ko if any problem (in this case, Consumer Dispatcher will resend the job)