Basic Usage of Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. Due to it is fast speed in storing and fetch data, it is widely used as a cache system in web applications. Lets see how it is used in a php example project.

<?php
  //connect to redis
  $redis = new Redis();
  $status = $redis->connect('127.0.0.1', 6379);

  if($status){
    echo "Connection to server sucessfully";
    echo "Server is running: " . $redis->ping();
  } else{
    echo "Connection to server failed";
  }


  Once connected, the connect method will return true;

List operation

Push element to a list :   lPush
Pop element from a list:  lPop
Get element from a list:  lGet
Length of the list:         ILen

    <?php

       error_reporting(E_ALL);
       ini_set('display_errors', 1);

       //connect to redis
       $redis = new Redis();
       $status = $redis->connect('127.0.0.1', 6379);

       if($status){
         echo "Connection to server sucessfully\n";
       }else{
         echo "Connection to server failed\n";
       }

       $redis->delete('list1');

       //list
       $redis->lPush('list1', '1');
       $redis->lPush('list1', '2');
       $redis->lPush('list1', '3');
       $redis->lPush('list1', '4');

       for($i = 0; $i < 4; $i++){
         $result = $redis->lGet('list1', $i);
         echo "element in postion " . $i ." : ". $result . "\n";
       }

       $result = $redis->lPop('list1');
       echo "poped element : " . $result . "\n";

       //get the length of the list
       $result = $redis->lLen('list1');
       echo "length of the list : " . $result . "\n";

       //get the size of the list
      $result = $redis->lSize('list1');
      echo "size of the list : " . $result . "\n";

Hash Map

add element to a hash table :   hSet
get element from a hash table:  hGet
does a key exists?:  hExists
Length of the hash table:         hLen

   //hash map
   $redis->hSet("hash1", "abc", 1);
   $redis->hSet("hash1", "mvp", 2);
   $redis->hSet("hash1", "vip", 3);

   $result = $redis->hGet('hash1', "abc");
   echo "hash element abc: " . $result . "\n";
   $result = $redis->hGet('hash1', "mvp");
   echo "hash element abc: " . $result . "\n";
   $result = $redis->hGet('hash1', "vip");
   echo "hash element abc: " . $result . "\n";

   $result = $redis->hExists('hash1', "vip");
   echo "hash element abc exists? " . $result . "\n";
   $result = $redis->hExists('hash1', "tip");
   echo "hash element abc exists? " . $result . "\n";

   $result = $redis->hLen('hash1');
   echo "hash table abc length: " . $result . "\n";