Thursday 1 May 2014

installing redis chat application

First step

Redis, it is an open source advanced key-value database storage system, works like NoSQL database. Redis operations can be executed on the server side and reduce the client's workload. It is used for caches to speed up web applications

For this tutorial, you will need :

Basic idea

In this configuration, imagine an existing chat system done with only PHP, the PHP got few ajax requests :
  • start chat
  • stop chat
  • publish message
The start chat will send previous message (if there is), and start a long polling request to server side PHP, everytime there is a new message, the long polling recieve answer and restart. The stop chat will of course stop this long polling. And publish message will send a message to PHP system (which will cause start system to get the message and start again).
This is how is done many chat system using only PHP. But this system is not the best, the long polling use too much server.
Node.JS with socket.io provide (not in all case) a webSocket interface to work with, wich is extremely good for server performance.
The idea behind this tutorial is to show a basic example using redis to remove the long polling part from PHP and transfert it to Node.JS. In this case you will only modify few request to get it working, and keep the already-working PHP system.

Using Redis

Redis got a PubSub functionality (publish/subscribe), we will use it in this way :
The long polling part is now on Node.JS side (wich is now not long polling but websocket), PHP keep everything else (user login, start chat, stop chat, send message), the start and stop will not do long polling, just send event to Node.JS.
So PHP will only publish event to Redis, while Node.JS will subscribe to channel to perform actions related.

Basic usage in PHP

For this example, i show the most basic example possible, do what you want with to improve you PHP system with Node.JS (i will not show a fully working example of chat system).
The purpose is to send an event from PHP to redis, and catch this event in Node.JS.
First of all, you need on PHP side Predis. Copy thoose files on your PHP server side, no need to configure anything else. Basically it’s classes for using redis instance. We use here the basic redis configuration on localhost and port 6379 :

REDIS OPEN SOURCE CHAT

Download

Redis uses a standard practice for its versioning: major.minor.patchlevel. An even minor marks a stable release, like 1.2, 2.0, 2.2, 2.4, 2.6, 2.8.Odd minors are used for unstable releases, for example 2.9.x releases are the unstable versions of what will be Redis 3.0 once stable.



2.8.9 Stable Redis 2.8 provides significant improvements like: Replication partial resynchronization, IPv6 support, config rewriting, keyspace changes notifications via Pub/Sub, and more. See the Release Notes for a full list of changes in this release. Download

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
//First we load the Predis autoloader
require(dirname(__FILE__)."/Predis/Autoloader.php");
//Register all classes
Predis\Autoloader::register();
//Now we can start creating a redis client to publish event
$redis = new Predis\Client(array(
    "scheme" => "tcp",
    "host" => "127.0.0.1",
    "port" => 6379
));
//Now we got redis client connected, we can publish event (send event)
$redis->publish("the_channel", "this is a test");
?>
With this extremely easy and basic example, everytime somebody will access this page, it will publish and event on channel "the_channel" with content "this is a test". Of course, you can send JSON, XML, what you want, wich can be pretty helpfull for Node.JS (especially JSON)
All we do now, is to put a Node.JS running in background, waiting for Redis to catch this event.
Before doing that, be sure you get the redis client : "npm install redis" which will be used here by Node.JS to connect to redis server.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var app         = require("http").createServer(handler),
    fs      = require("fs"),
    redis   = require("redis");
app.listen(7070);
//You can specify port and host : redis.createClient(PORT, HOST, options)
var clientSusbcribe = redis.createClient();
clientSusbcribe.subscribe("the_channel");
clientSusbcribe.on("message", function(channel, message){
    console.log("client channel recieve from channel : %s, the message : %s", channel, message);
});
//On client incomming, we send back index.html
function handler(req, res){
    fs.readFile(__dirname + "/index.html", function(err, data){
        if(err){
            res.writeHead(500);
            return res.end("Error loading index.html");
        }else{
            res.writeHead(200);
            res.end(data);
        }
    });
}
That’s almost done, nothing more to do. Feel free to combine with redis tuto for session sharing, and you should now have a fully working link between PHP and Node.JS…
Here is a small screenshot of this small code :
redis PubSub using PHP and Node.JS
Be carefull, don’t forget Node.JS only listen "the_channel" to perform this, if you change channel on PHP you should do the same on Node.JS. Don’t forget also you can have many channel for many event type, which can be pretty helpfull. The clientSubscribe can handle many channel if needed (better to keep only one client for all channel)

For Windows

Download unofficial version click here, go to bin directory then releases and extract redisbin.zip run redis-server.exe file

Download php_redis.dll copy into PHP extension folder.

Add Extension on php.ini

extension php_redis-2.1.3-5.3-ts.dll

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete