RabbitMq encapsulating php

Simply encapsulate a rabbitmq class (business code is written casually)

First, account password configuration


    return $arr = [
        'RabbitMq' => [
            // Rabbitmq service address
            'host' => '',
            // Rabbitmq service port
            'port' => '5672',
            // Rabbitmq account
            'login' => 'guest',
            // Rabbitmq password
            'password' => 'guest',

Base class base.php

include dirname(__FILE__).'/object.php';
include dirname(__FILE__).'/config.php';
class RabbitMq implements object
    //Save static member variables for class instances
    static private $_instance;
    static private $_conn;
    static private $amp ;
    static private $route = 'key_1';
    static private $q ;
    static private $ex ;
    static private $queue;
    public static function getInstance(){
        global $arr;
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($arr['RabbitMq']);
            return self::$_instance;
        return self::$_instance;

    private function __construct($conn)
        //Create connections and channel s
        $conn = new AMQPConnection($conn);
        if(!$conn->connect()) {
            die("Cannot connect to the broker!\n");
        self::$_conn = new AMQPChannel($conn);
        self::$amp = $conn;
    /* *
     * parm Switch name
     * parm Queue name
     * */
    public function listen($exchangeName,$queuename){
        self::$queue = $queuename;
        return $this->setExchange($exchangeName,$queuename);

    //Connecting switches
    public function setExchange($exchangeName,$queueName){
        //Create switch
        $ex = new AMQPExchange(self::$_conn);
        self::$ex = $ex;

        $ex->setType(AMQP_EX_TYPE_DIRECT); //direct type
        $ex->setFlags(AMQP_DURABLE); //Persistence
        return self::setQueue($queueName,$exchangeName);

    //Create queue
    private static function setQueue($queueName,$exchangeName){
    //  Create queue
        $q = new AMQPQueue(self::$_conn);

    // Used to bind queues and switches
        $routingKey = self::$route;
        $q->bind($exchangeName,  $routingKey);
        self::$q = $q;

 * consumer
 * $fun_name = array($classobj,$function) or function name string
 * $autoack Auto answer or not
 * function processMessage($envelope, $queue) {
        $msg = $envelope->getBody();
        echo $msg."\n"; //Processing messages
        $queue->ack($envelope->getDeliveryTag());//Manual response
    public function run($func, $autoack = True){
        if (!$func || !self::$q) return False;
            if ($autoack) {
                if(!self::$q->consume($func, AMQP_AUTOACK)){
//                    self::$q->ack($envelope->getDeliveryTag());
                   //After failure, it will enter noack queue by default. It will be called again next time it is reopened. It is not clear that the callback configuration should give a failure feedback here

    private static function closeConn(){

    public function pushlish($msg){
        while (1) {
            if (self::$ex->publish(date('H:i:s') . "user" . "register", self::$route)) {
                //Write file and other operations
                echo $msg;

    //Wei clone method prevents objects from being copied and cloned
    public function __clone()
        trigger_error('Clone is not allow!', E_USER_ERROR);


Consumption listening class (one operation corresponds to one class)

include dirname(__FILE__).'/base.php';
class Add
    public static function run(){

        $dbms='mysql';     //Database type
        $host='127.0.01'; //Database host name
        $dbName='test';    //Database used
        $user='root';      //Database connection user name
        $pass='admin';          //Corresponding password

        try {
            $dbh = new PDO($dsn, $user, $pass); //Initializing a PDO object
            /*You can also do a search operation
            foreach ($dbh->query('SELECT * from FOO') as $row) {
                print_r($row); //You can use echo($GLOBAL); to see these values
            $dbh = null;
        } catch (PDOException $e) {
            die ("Error!: " . $e->getMessage() . "<br/>");
//By default, this is not a long connection. If you need a long connection to the database, you need to add the last parameter: array (PDO:: attr)_ Persistent = > true) becomes this:
        $db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
        $sql = 'INSERT INTO `test`.`t_reg`(`names`) VALUES (9)';
        $row = $db->query($sql);
           return false;
            echo 'OK';

$consume = new Add();
//$s = rabbitmq:: getinstance() - > Listen ('jiahuanji ',' queue1 ') - > run (array ('consume,' run '))); bring run function into consume as callback, add $funname and code stickiness in consume
$s = RabbitMq::getInstance()->listen('jiaohuanji','queue1')->run(array($consume,'run'));

push class (sender)

include "base.php";

RabbitMq::getInstance()->listen('jiaohuanji','queue1')->pushlish('Request sent');


    interface object
        public static function getInstance();

monitor add.php

Execution send.php Simple orbit operation

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced. There is no sense of direction when they write too much business code. I don't know where to start to improve. For this, I collated some data, including but not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, SW For advanced advanced dry goods of many knowledge points, such as oole, Swoft, Kafka, Mysql optimization, shell script, Docker, microservice, Nginx, etc., you can share what you need for free. You need to stamp here PHP advanced architect > > > free access to video and interview documents

Tags: Programming PHP RabbitMQ Database PDO

Posted on Tue, 02 Jun 2020 10:19:54 -0400 by mrtechguy