How does PHP continue to listen to Redis message subscriptions and push them to the front end?
Overview:
In many web applications, real-time push messages are a common requirement. When we need to send messages to the front end in real time, we often use polling or long polling to obtain the latest data. However, this method consumes a lot of server resources, and the response speed is not real-time enough. Using the message queue mechanism of Redis can solve this problem very well. This article will introduce how to use PHP to continuously monitor Redis message subscriptions and push messages to the front end in real time.
Implementation steps:
sudo apt-get install redis-server sudo apt-get install php-redis
<?php $redis = new Redis(); $redis->connect('localhost', 6379); $redis->subscribe(['channel_name'], function ($redis, $channel, $message) { // 将消息推送到前端 echo "<script>console.log('New message:', " . $message . ");</script>"; ob_flush(); flush(); }); $redis->close(); ?>
In this code, first connect to the local Redis server through the connect method of Redis, and use the subscribe method to subscribe to the specified channel (channel_name). When a message arrives, the callback function will push the message to the front end.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div id="message-holder"></div> <script> function showMessage(message) { $('#message-holder').append('<p>' + message + '</p>'); } </script> </body> </html>
In this code, we The jQuery library is used to operate the DOM and the received message is displayed on the page by defining a showMessage function.
<?php $redis = new Redis(); $redis->connect('localhost', 6379); $redis->subscribe(['channel_name'], function ($redis, $channel, $message) { //将消息推送到前端 echo "<script>window.parent.showMessage('" . $message . "');</script>"; ob_flush(); flush(); }); $redis->close(); ?>
The key in this code Part of it is the echo statement, which passes the message to the front-end page for display by calling the showMessage function.
php subscribe.php
Now, when a new message arrives, the PHP script will push the message to the front-end page for display in real time.
Summary:
Through the above steps, we can use PHP to continuously monitor Redis message subscriptions and push messages to the front-end page in real time. In this way, the function of pushing messages in real time can be realized, and the problem of wasting server resources and insufficient real-time response speed caused by using polling or long polling methods can be avoided. In addition, the code can be optimized and expanded according to actual needs to improve system performance and stability.
The above is the detailed content of How does PHP continue to listen to Redis message subscriptions and push them to the front end?. For more information, please follow other related articles on the PHP Chinese website!