The popular Redis storage engine is an excellent and must-have tool in any software developer's arsenal. The in-memory storage engine allows for blazingly fast storage and retrieval of data, up to an impressive 32 million queries per second, making it a prime complement to any major database engine.

Let's dive in, and learn how to speed up our online operations.

Redis: Pros vs. Cons

The greatest benefit of Redis is that it's a purely in-memory data store, meaning it's blazingly fast as the database is stored within RAM hence no file I/O operations to the hard drive are required.

Other added benefits are its simplicity, clustering support via Redis-cluster, plus its support for eight different data types providing you the flexibility necessary to store and manage your data as needed.

However, its greatest downfall is also the fact it's purely an in-memory data store, hence comes with size limitations. It depends on your server infrastructure, but for the sake of this article and simplicity, your typical Redis database will only hold a maximum of 2-4GB of data.

This means Redis is used to compliment the popularly used database engines such as mySQL, PostgreSQL and MongoDB, and is not meant as a replacement. Main uses for Redis include a cache, temporary/recent data that will expire in a short period of time, or small pieces of data that are frequently accessed.

How to Install Redis

Assuming you're running Ubuntu or any Linux distro that contains the apt-get command, to install Redis simply run the following command in terminal:

        sudo apt-get install redis-server
    

Next, check to ensure Redis has been successfully installed. Within the terminal, run the command:

        redis-cli --version
    

This should print the version of Redis you're running, and assuming so, run the following command to connect to Redis:

        redis-cli
    

This will give you a non-standard Redis prompt within the terminal, which looks something like:

        127.0.0.1:6379>
    

String Commands

Every entry into Redis is identified by a key, which can be any non-whitespace string you wish. Strings only contain a single value, and for example, run the following commands at the Redis prompt to set a value to a couple of keys.

        127.0.0.1:6379>  set full_name "John Doe"
127.0.0.1:6379> set units 5

You may now list all keys currently within the Redis database with the keys command.

        127.0.0.1:6379>  keys *
    

This will result in displaying the two keys you previously set, full_name and units. You may see the value of these keys with the get command.

        127.0.0.1:6379>  get full_name
"John Doe"
127.0.0.1:6379> get units
5

Deleting keys can easily be done with the del command.

        127.0.0.1:6379>  del full_name
    

It's also possible to quickly increment an integer with the hincrby command. The following will increment the "units" key from 5 to 7.

        127.0.0.1:6379>  incrby units 2
    

List Commands

Lists in Redis are one-dimensional arrays with a specific order, and allow for duplicate items within different positions of the list. Items can be added to the left or right of a list with the lpush and rpush commands.

        127.0.0.1:6379>  lpush colors blue
127.0.0.1:6379> rpush colors red yellow green

As you can see from the above example, you may push multiple items to a list within a single command. We can now view all items in the list by using the lrange command.

        127.0.0.1:6379>  lrange colors 0 -1
    

There are two integers at the end of the command, the first which defines the position within the list to begin at, and the second is the number of items to return with -1 meaning all items. The result of the above command will be, blue, red, yellow, green.

You may also remove items off either end of a list using the lpop and rpop commands.

        127.0.0.1:6379>  lpop colors
blue
127.0.0.1:6379> rpop colors
green

You may also get the number of elements in a list with the llen command.

        127.0.0.1:6379>  llen colors
(integer) 2

Last, you may remove an element from a list via the lrem command.

        127.0.0.1:6379>  lrem colors 1 green
(integer) 1

The lrem command begins with the list name, followed by the number of occurrences to remove, and the name of the element to remove. It will return the number of occurrences found and removed from the list.

Hash Commands

One of the most popular data types in Redis are hashes, which allow you to store multiple key-value pairs within a single entry. The key does not already need to exist, and you define key-value pairs anytime with the hset command.

        127.0.0.1:6379>  hset user:581 full_name "Jane Doe"
127.0.0.1:6379> hset user:581 points 500

You can also define multiple key-value pairs of a hash within a single command using the hmset command.

        127.0.0.1:6379>  hmset user:581 email jane@domain.com gender F
    

The hash identified by the key user:581 now have a total of four key-value pairs, all of which can be easily retrieved with the hgetall command.

        127.0.0.1:6379>  hgetall user:581
1) "full_name"
2) "Jane Doe"
3) "points"
4) "500"
5) "email"
6) "jane@domain.com"
7) "gender"
8) "F"

You can also get the value of a single key-value pair within a hash by using the get command.

        127.0.0.1:6379>  hget user:581 email
"jane@domain.com"

For any integers within the hash, you can increment them by a specified amount with the code hincrby command.

        127.0.0.1:6379>  hincrby user:581 points 20
(integer) 520

The value of the points key within the hash has now been incremented by 20 to 520. A single key-value pair within a hash may be deleted with the hdel command.

        127.0.0.1:6379>  hdel user:581 gender
    

Alternatively, you may also delete a hash entirely including all key-value pairs by using the del command.

        127.0.0.1:6379>  del user:581
    

Expiring Redis Keys

Another excellent feature of Redis is the ability to automatically expire keys after a defined number of seconds using the expire command. Please note, you may only expire full keys and not singular elements within a list or hash. For example:

        127.0.0.1:6379>  expire full_name 10
    

This will set an expiration time of 10 seconds on the full_name key you created in the strings section. After running the above command, wait 10 seconds then try to retrieve the value of the key again.

        127.0.0.1:6379>  get full_name
(nil)

As expected, the key has now expired hence we get null as a result.

Connect to Redis With PHP

Now that you've learned the basics of how to store and retrieve data with Redis, it's time to connect it into your software. All programming languages have modules/extensions for Redis, but for this example, we'll be using PHP.

You first must install the PHP-Redis extension as it's not installed by default. Within the terminal, run the command.

        sudo apt-get install php-redis
    

Once installed, make sure to restart PHP-fpm so the extension is properly loaded. Here's some PHP code that connects to and interfaces with Redis.

        <?php

// Connect to redis
$conn = new redis();
try {
    $conn->connect('127.0.0.1', 6379, 5);
} catch (RedisException $e) {
    die("Unable to connect to redis");
}

// Set string
$conn->set('country', 'Canada');

// Get string
$value = $conn->get('country');
echo "Country is: $value\n";

// Define a profile
$profile = [
    'username' => 'mike',
    'full_name' => 'Mike Smith',
    'email' => 'mike@domain.com',
    'country' => 'Australia'
];

// Create a hash
$conn->hmset('user:188', $profile);

// Get all values of the profile hash
$values = $conn->hgetall('user:188');
print_r($values);

// Get only the e-mail address
$email = $conn->hget('user:188', 'email');
echo "E-mail is: $email\n";

// Expire the hash in 15 seconds
$conn->expire('user:188', 15);

The above example code should be quite straight forward. It first connects to Redis with a timeout of 5 seconds, then proceeds to set and get a string and hash. All Redis commands can be performed via OOP by calling them directly from the Redis object as exampled above.

You're on Your Way!

Congratulations, you've learned the basics of how to store and retrieve data with blazing speed via the Redis storage engine, including how to connect to and interface with Redis using PHP.

Please note, this article only covers the very basics, and the Redis Data Types page of the documentation is a great place to continue exploring Redis and all its functionality.