In this paper, we introduce the method of using Redis message queue to publish micro-blog, combined with specific examples to analyze PHP and Redis database operation message Queue to achieve micro-blog release of the relevant skills and considerations, the need for friends can refer to, hope to help everyone.
In some users publish content application, may appear 1 seconds tens of thousands of users simultaneously publishes the message situation, at this time uses the MySQL may appear "Too many connections" the error, of course the MySQL max_connections parameter set to the larger number, But this is a way to cure the symptoms. Using Redis's Message Queuing, the messages posted by the user are temporarily stored in the message queue, and then the data in the message queue is inserted into MySQL using multiple cron programs. This effectively reduces the high concurrency of MySQL. The specific implementation principle is as follows:
Existing Weibo publishing interface:
$weibo = new Weibo (), $uid = $weibo->get_uid (), $content = $weibo->get_content; $time = time (), $webi->post ($uid, $ Content, $time);
This method writes the microblog content directly to MySQL. The specific process is omitted.
Write the message to Redis:
$redis = new Redis (localhost,6379), $redis->connect (), $webiInfo = Array (' UID ' =>get_uid (), ' content ' =>get_ Content (), ' Time ' =>time ()), $redis->lpush (' Weibo_list ', Json_encode ($weiboInfo)); $redis->close ();
Extracting data from Redis:
while (true) { if ($redis->lsize (' weibo_list ') > 0) { $info = $redis->rpop (' weibo_list '); $info = Json_decode ($info); } else{ Sleep (1);} } $weibo->post ($info->uid, $info->content, $info->time);//When inserting data, you can insert multiple data at once to avoid circular insertion. A constant loop insert can cause deadlock problems.
tip: You can run multiple cron programs while inserting Message Queuing data into MySQL, and when a Redis server is unable to cope with large amounts of concurrency, use the consistent hash algorithm to distribute the concurrency to different redis servers.