Posts Issued in November, 2014

  • Console start
  • Basic Operators & Types
  • Jobs (Py)
  • Examples using PhpRedis

Commands for terminal

//To start a local instance:
redis-server
redis-cli -h my-host -p 1234 -a mypassword

Work with strings

//SET to store the value "fido" at key "server:name"
 
    SET connections 10
    INCR connections => 11
    INCR connections => 12
    DEL connections
    INCR connections => 1
 
    SET resource:lock "Redis Demo"
    EXPIRE resource:lock 120
/*
key resource:lock to be deleted in 120 seconds
to check - TTL - "-2" means that the key does not exist, "-1" never delete, new use SET  TTL will be reset
*/
    TTL resource:lock => 113 //del in 113 seconds

Commands for Lists

//append list friends at the end
    RPUSH friends "Alice" 
//append list at the start (1st element)
    LPUSH friends "Sam" 
//subset of the list
    LRANGE friends 0 -1 => 1) "Sam", 2) "Alice", 3) "Bob"
    LRANGE friends 1 2 => 1) "Alice", 2) "Bob"
 
    LLEN friends => 3
    LPOP friends => "Sam"
    RPOP friends => "Bob"

A Set is similar to a List, except it does not have a specific order and each element may only appear once.

SADD superpowers "flight"
    SREM superpowers "reflexes"
    SISMEMBER superpowers "flight" => 1
    SMEMBERS superpowers => 1) "flight", 2) "x-ray vision"
    SUNION superpowers birdpowers => 1) "pecking", 2) "x-ray vision", 3) "flight"

A Sorted Set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set.

ZADD hackers 1940 "Alan Kay"// 1940 used for sorting ONLY
    ZRANGE hackers 2 4 => 1) "Claude Shannon", 2) "Alan Kay", 3) "Richard Stallman"

Hashes are maps between string fields and string values, so they are the perfect data type to represent objects

HMSET user:1001 name "Mary Jones" password "hidden" email "mjones@example.com"
    HGET user:1001 name => "Mary Jones"
    HGETALL user:1000
    HSET user:1000 visits 10
    HINCRBY user:1000 visits 1 => 11
    HINCRBY user:1000 visits 10 => 21
    HDEL user:1000 visits
    HINCRBY user:1000 visits 1 => 1

Work with Jobs using Py Now using this approach in Laravel

/*
A background process runs and hits various json and RSS services to get current jobs. Our approach will be to hold each job in its own String value. The key format will be job:SOURCE:SOURCE_ID. So, if we give github a source of 1, then the job at http://jobs.github.com/positions/73c9e09a-09b0-11e1-9819-355783013ce0 will have a key of job:1:73c9e09a-09b0-11e1-9819-355783013ce0. The value for this key will be the job details.
 
Assuming we've parsed our job into a hash, saving it into Redis will look something like:
*/
def save(job)
  key = "job:#{job[:source]}:#{job[:source_id]}"
  redis.set(key, job.to_json)
end
 
/*display the jobs in reverse chronological order
Using this approach jobs are sorted by date we process them, rather than we the jobs are posted
*/
def save(job)
  key = "job:#{job[:source]}:#{job[:source_id]}"
  redis.multi do  #begins a transaction
    redis.set(key, job.to_json)
    redis.lpush('jobs', key)
  end
end
 
//map to when the job was posted - Use a sorted set
def save(job)
  key = "job:#{job[:source]}:#{job[:source_id]}"
  redis.multi do
    redis.set(key, job.to_json)
    redis.zadd('jobs', job[:created_at], key) # :created_at is already an integer (seconds since ..)
  end
end
 
//Listing Jobs
def get_latest_jobs
  keys = redis.zrevrange('jobs', 0, 150)
  jobs = redis.mget(*keys)
  jobs.map do |j|
    job = JSON.parse(j)
    job['created_at'] = Time.at(job['created_at'])
    job
  end
end
 
//Cleaning Jobs
redis.multi do
  keys = redis.zrange('jobs', 0, -300)
  redis.del(*keys)
  redis.zrem('jobs', *keys)
end

PhpRedis

Main Commands

$redisClient -> connect(hostOrUnixPath”, “port”, “timeOut”, “reservedInterval);
//get the value associated with the specified key 
$redisClient -> get('key', 'value');
//get the multiple value
$arrKeys = array(keyA”, “keyB”, “keyC);
$redisClient -> mget($arrKeys);
$redisClient -> set('key');
$redisClient -> setex('key', 3600, 'value' );//expiration
$redisClient -> del('key');
$redisClient -> exists('key');
$redisClient -> close();

Code Examples PHP Redis

<?php 
 
  $redisObj = new Redis(); 
 
  function openRedisConnection( $hostName, $port){ 
    global $redisObj; 
    $redisObj->connect( $hostName, $port );
    return $redisObj; 
  } 
 
  function setValueWithTtl( $key, $value, $ttl ){ 
    try{ 
        global $redisObj; 
        // setting the value in redis
        $redisObj->setex( $key, $ttl, $value );
    }catch( Exception $e ){ 
        echo $e->getMessage(); 
    } 
  } 
 
  function getValueFromKey( $key ){ 
    try{ 
        global $redisObj; 
        // getting the value from redis
        return $redisObj->get( $key);
    }catch( Exception $e ){ 
        echo $e->getMessage(); 
    } 
  } 
 
  function deleteValueFromKey( $key ){ 
    try{ 
        global $redisObj; 
        // deleting the value from redis
        $redisObj->del( $key);
    }catch( Exception $e ){ 
        echo $e->getMessage(); 
    } 
  } 
 
  function convertToArray( $result ){ 
    $resultArray = array(); 
 
    for( $count=0; $row = $result->fetch_assoc(); $count++ ) { 
        $resultArray[$count] = $row; 
    } 
 
    return $resultArray; 
  } 
 
  function executeQuery( $query ){ 
     $mysqli = new mysqli( 'localhost',  'username',  'password',  'someDatabase' ); 
 
     if( $mysqli->connect_errno ){ 
       echo "Failed to connect to MySql:"."(".mysqli_connect_error().")".mysqli_connect_errno(); 
     } 
 
     $result =  $mysqli->query( $query ); 
     // Calling function to convert result  to array
     $arrResult = convertToArray( $result );
 
     return $arrResult;      
  }  
 
  $query = 'select * from sometable limit 1'; 
  // Calling function to execute sql query
  $arrValues = executeQuery( $query );
 
  // Making json string
  $jsonValue = json_encode($arrValues);
 
  // Opening a redis connection
  openRedisConnection( 'localhost', 6379 );
 
  // Inserting the value with ttl =  1 hours
  setValueWithTtl( 'somekey1', $jsonValue, 3600);
 
  // Fetching value from redis using the key. 
  $val = getValueFromKey( 'somekey1' ); 
 
  //  Output:  the json encoded array from redis 
  echo $val;
 
  // Unsetting value from redis
  deleteValueFromKey( $key );