The benefits of Redis message queuing lie in its lightweight, high concurrency, delay sensitivity, application scenarios such as real-time data analysis, seconds kill counters, caching, etc

Redis does message queuing to solve the problem:

1. Message reliability: there is no corresponding mechanism to ensure message consumption. When consumers fail to consume, the message body is lost and needs to be handled manually. The producer simply inserts data into the queue, regardless of whether the consumer succeeds in consuming it.

2, the consumer hangs the message will not be lost, but the consumer needs to be retriggered to continue consuming the message.

The code is as follows:

Lib.php is a utility file that contains database connections and Redis connections:

** @param $host * @param $username * @param $password * @param $database * @return mysqli */ function getDBConnection($host, $username, $password, $database){ $connection = new mysqli('p:'.$host, $username, $password, $database); if (! $connection) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } mysqli_query($connection, "set names 'utf8'"); return $connection; } @param $host * @param $port * @param string $password * @param int $database * @return Redis */ Function getRedis($host='127.0.0.1', $port='6379', $password=null, $database=0){$redis = new redis (); if(! $redis->connect($host, $port)){die($redis->connect($host, $port)); } if(! empty($password) && ! $redis->auth($password)){die(" redis failed: password error "); } if($database){ $redis->select($database); $subscribe ->setOption(redis ::OPT_READ_TIMEOUT, -1); $subscribe ->setOption(redis ::OPT_READ_TIMEOUT, -1) return $redis; } / print the message log * * * * * @ $MSG param * / function stdout ($MSG = null) {$MSG = '['. The date (' Y -m - d H: I: s').'] '. $MSG. The CRH (10);; fwrite(STDOUT, $msg); }Copy the code

Register.php is the message publisher, annotating the part of the code that stores the message to the database.

First, you want the message to be stored in the register_USERS queue with a register_USERS key. Value is a list into which all messages are stored. The command to view data with redis-cli is:

LRANGE register_users 0 -1

Register. PHP:

require './lib.php'; $name = $argv[1]; $mobile = $argv[2]; If (empty ($name) | | the empty ($mobile)) {die (" parameter error "); } // $connection = getDBConnection('localhost:3306', 'root', 'root', 'blog'); // // start transaction // mysqli_begin_TRANSACTION ($connection); // $sql = "insert into mq_user(name, mobile) values ('$name', '$mobile')"; // if(! Mysqli_query ($connection, $SQL)){// die(" failed to write user information; ".$connection->error); // } $redis = getRedis(); $redis->lpush('register_users', json_encode(array('name'=>$name, 'mobile'=>$mobile), JSON_UNESCAPED_UNICODE)); if($result === false){ mysqli_rollback($connection); Die (" Failed to add message queue "); $redis->publish('register_success', 'ok'); Mysqli_commit ($connection); // $connection->close(); $redis->close();Copy the code

Work.php acts as a consumer of messages

require './lib.php'; $redis = getRedis(); $redis->subscribe(['register_success'], function ($instance, $channelName, $message) { if($channelName == "register_success" && $message = "ok") { $redis = getRedis(); while($redis->lsize("register_users")>0) { $arr = $redis->brPop(['register_users'], 20); if(count($arr)) { $userInfo = json_decode($arr[1], true); Stdout (" new user info :"); Stdout (" name: ". $the userInfo [' name ']); $userInfo['mobile']; $userInfo['mobile']; stdout(); sleep(3); }}}});Copy the code

Register.php puts the message into the register_USERS queue of Redis, and then publishes to block the register_SUCCESS message. Work.php uses subscribe to subscribe register_success messages. Upon receipt of the register_SUCCESS message, the register_USERS message is read for processing.

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database