John Siu
John Siu

Reputation: 5092

PHP AMQP (not phpamqplib) error when using thread

I am trying to make a simple AMQP client into multithread. The following code work if the I don't extend Publish with Thread:

<?php

include ('../JS-amqp-include.php');

$mypid = getmypid();

echo "PID: $mypid\n";

class Publish extends Thread {

    private $co;// connection
    private $ch;// channel
    private $ex;// exchange
    private $mypid, $thread_id;

    public function __construct($connection = '') {
        $this->mypid = getmypid();

        $this->co = new AMQPConnection();
        $this->co->setHost(HOST);
        $this->co->setLogin(USER);
        $this->co->setPassword(PASS);
        $this->co->setVHost(VHOST);
        $this->co->connect();           // <-- Fail here!!!!

        $this->ch = new AMQPChannel($this->co);

        $this->ex = new AMQPExchange($this->ch);
        $this->ex->setName(X_DIR);
        $this->ex->setType(XT_DIR);
        $this->ex->setFlags(AMQP_DURABLE);
        $this->ex->declareExchange();
    }

    public function run($cycle = 10, $input = '') {
        for ($i = 1; $i <= $cycle; $i++) {
            $msg = $this->mypid.':'.$input.':'.$i;
            $this->ex->publish($msg);
        }
    }
}

$time_start = microtime(true);

$pub = new Publish();
$pub->run(100, 'thread');
$time_end      = microtime(true);
$time_duration = $time_end-$time_start;
echo "Duration: $time_duration Sec.\n";

?>;

Following is output with error:

PID: 2276
PHP Fatal error:  Uncaught exception 'AMQPConnectionException' with message 'Socket error: could not connect to host.' in /home/john/rmq/php/Amqp/JS-amqp-publish-thread.php:24
Stack trace:
#0 /home/john/rmq/php/Amqp/JS-amqp-publish-thread.php(24): AMQPConnection->connect()
#1 /home/john/rmq/php/Amqp/JS-amqp-publish-thread.php(45): Publish->__construct()
#2 {main}
  thrown in /home/john/rmq/php/Amqp/JS-amqp-publish-thread.php on line 24

Anyone has idea why this happen or how to fix?

Rabbitmq is running at HOST.

The program works perfectly if 'extends Thread' is removed from class Publish declaration. The above code is not even using thread yet. I just extend the class and it break.

System Info

OS: Ubuntu 15.10

Rabbitmq-c (apt-get install)

librabbitmq-dev:amd64 0.5.2-2 amd64 AMQP client library written in C - Dev Files librabbitmq1:amd64 0.5.2-2 amd64 AMQP client library written in C

I follow this link to re-compile Ubuntu PHP package to support ZTS.

PHP 5.6.11-1ubuntu3.2 (cli)

Copyright (c) 1997-2015 The PHP Group

Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

PHP module

amqp 1.6.0 stable

pthreads 2.0.10 stable

Upvotes: 0

Views: 947

Answers (0)

Related Questions