With the continuous development of Internet technology, our performance requirements for network applications are getting higher and higher. Under this premise, server-side push service, as a real-time communication solution, is adopted by more and more applications. This article will introduce how to use Memcache and PHP to implement high-performance server-side push services.
1. What is server-side push service?
Server-side push service means that the server actively sends data to the client without requiring the client to actively request data. For example, in a chat room, after a user sends a message, all online users can receive the message without each user having to request it. This can greatly enhance real-time performance and also reduce the pressure on the server.
2. The role of Memcache
Memcache is a tool for caching data. Its function is to store data in memory to speed up the reading and writing of data. In the server-side push service, the role of Memcache is to cache the messages that need to be sent to reduce the pressure on the server and database.
3. Use PHP to implement server-side push service
Next, we will use PHP to implement server-side push service. This article will assume that we already have a chat room system, which contains the following three parts:
The online user list refers to the current chat room List of users in the room. We need to cache the online user list in Memcache for quick access.
The message list refers to the list of messages sent by all users. We need to cache the message list in Memcache for quick access. At the same time, we need to add a timestamp field to the message list to facilitate the client to determine whether there are new messages.
Push service refers to a service that actively sends messages that need to be pushed to the client. In our system, we will use WebSocket to implement push service.
The following are the detailed implementation steps:
We can add the user to the online user list when they log in. Then, when the user logs out, remove them from the list of online users. The online user list is cached as follows:
$memcache = new Memcache;
$memcache->addServer('localhost', 11211);
// Add the online user list Cache
$onlineUsers = array('user1', 'user2', 'user3');
$memcache->set('online_users', $onlineUsers, 0, 0);
// Get the online user list from the cache
$onlineUsers = $memcache->get('online_users');
We can When a user sends a message, add it to the message list. Then, in the push service, send the message list to the client. We need to add a timestamp field to the message list to facilitate the client to determine whether there are new messages. The message list is cached as follows:
$memcache = new Memcache;
$memcache->addServer('localhost', 11211);
// Add the message list to the cache
$messages = array(
array('user' => 'user1', 'message' => 'hello', 'timestamp' => time()), array('user' => 'user2', 'message' => 'world', 'timestamp' => time())
);
$memcache->set('messages', $messages, 0, 0);
// Get from cache Message list
$messages = $memcache->get('messages');
We will use WebSocket to implement push service. WebSocket is a real-time communication protocol that can be used in modern browsers. In PHP, we can use Ratchet to implement WebSocket. The following is how the push service is implemented:
//Introduce the Ratchet library
require __DIR__.'/vendor/autoload.php';
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
// WebSocket push service
class Chat implements MessageComponentInterface
{
protected $clients; public function __construct() { $this->clients = new SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); } public function onMessage(ConnectionInterface $from, $msg) { $memcache = new Memcache; $memcache->addServer('localhost', 11211); // 获取在线用户列表和消息列表 $onlineUsers = $memcache->get('online_users'); $messages = $memcache->get('messages'); // 发送消息给所有客户端 foreach ($this->clients as $client) { $client->send(json_encode(array( 'type' => 'message', 'online_users' => $onlineUsers, 'messages' => $messages ))); } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); } public function onError(ConnectionInterface $conn, Exception $e) { $conn->close(); }
}
// Create WebSocket server and start
$app = new RatchetApp ('localhost', 8080);
$app->route('/chat', new Chat);
$app->run();
4. Client implementation
The client can be implemented using any modern browser. The following is the HTML and JavaScript code of the client:
< head>
<title>WebSocket Chat</title>
<ul id="messages"></ul> <form action=""> <input id="message" type="text"> <button>Send</button> </form> <script> var ws = new WebSocket("ws://localhost:8080/chat"); ws.onmessage = function(event) { var data = JSON.parse(event.data); // 更新在线用户列表 var onlineUsers = data.online_users; for (var i = 0; i < onlineUsers.length; i++) { // add online user to list } // 更新消息列表 var messages = data.messages; for (var i = 0; i < messages.length; i++) { // add message to list } }; document.querySelector("form").addEventListener("submit", function(event) { event.preventDefault(); var input = document.querySelector("input#message"); ws.send(input.value); input.value = ""; }); </script>