William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP and Redis Server

PHP and Redis Server

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

Redis server can be used as a session handler, which is especially useful if you are using a multi-server architecture behind a load balancer.
Redis also has a publish/subscribe system, which is great for creating an online chat or a live booking system.
I used Redis server with NodeJS before; however and definitely, Redis Server is also available for PHP. Here is a helpful article:

http://phpmaster.com/an-introduction-to-redis-in-php-using-predis/

The following are the steps to install Redis-server, and make it work in PHP.

//1. install redis-server
wget http://redis.googlecode.com/files/redis-2.2.4.tar.gz
tar -zxf redis-2.2.4.tar.gz
cd redis-2.2.4
make
sudo make install

//2. run it, sumple way, you can also use: 
//sudo update-rc.d redis-server defaults to make it run when start.
$ /usr/local/bin/redis-server &

Now Redis server is done. After that, we make it work with PHP.
For PHP, Redis client library is Predis, we can get the sources from github:

$ git clone git://github.com/nrk/predis.git

After install Redis server and Predis interface, we now use PHP to connect and operate the session server. A testing example like this:

<?php
require "predis/autoload.php";
Predis\Autoloader::register();

// since we connect to default setting localhost
// and 6379 port there is no need for extra
// configuration. If not then you can specify the
// scheme, host and port to connect as an array
// to the constructor.
try {
    $redis = new Predis\Client();
/*
    $redis = new Predis\Client(array(
        "scheme" => "tcp",
        "host" => "127.0.0.1",
        "port" => 6379));
*/
    echo "Successfully connected to Redis";
}
catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}

Pretty simple, and should return ‘Successfully connected to Redis’. A more test for Redis key-value store is like this:

<?php
$redis->set("any_key", "Hi Redis for php by using predis!");
$value = $redis->get("any_key");
print_r($value);
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 73 other followers

%d bloggers like this: