Caching Services (also known as in-memory databases) like Redis and Memcached are being heavily used in today’s web applications. These in-memory databases are faster than traditional databases like MySQL, Oracle, MongoDB, CouchDB, etc. for one important reason that this data is stored in RAM rather than on Harddisks. Both Redis and Memcached are accessible via their REST APIs.
When it comes to Read/Write operations, Memcached and Redis performances are almost identical, both are lightning fast. Both Memcached and Redis belong to the NoSQL family of databases, and both are based on a key-value data model. Structure of information stored in these databases can be matched to the JSON documents.
Referring to the features, Redis is more feature rich database than Memcached.
Both databases have their pros and cons. In this article, we will create a simple Redis cluster on Elasticache and then access this cluster from our PHP code that is placed on an EC2 instance in the same geographical region (we use Mumbai in this example). The foremost requirement before proceeding with this tutorial is that you need to have a verified AWS account, working knowledge of AWS console, PHP and Redis. You are also required to have basic Linux command line knowledge so that you can install basic tools like Zip, Unzip, Redis CLI and PHP on the EC2 Linux Instance. Lastly, the preferred region needs to be selected from the top right corner of your AWS console. Once done, login to your AWS console to proceed with the following steps.
[Step #1: Creating Security Group]
This is the most important step in setting up your Redis cluster. For this example, we will create our own security group by the name of ‘eduonix-sg’. While creating this security group, make sure to set the following two inbound rules:
—————————————- —————————————-
First Inbound Rule
—————————————- —————————————-
Type: Custom TCP
Protocol: TCP
Port Range: 6379
Source: Anywhere
—————————————- —————————————-
Second Inbound Rule
—————————————————— ————————–
Type: SSH
Protocol: TCP
Port Range: 22
Source: Anywhere
This security group will be assigned to both the EC2 instance and Elasticache cluster. The first rule is set to make our Redis cluster accessible from within our EC2 instance. The second rule is being created to allow our EC2 instance to be accessible via SSH from our local computer. The outbound rule will be set to its default value.
Please note: – By default, Elasticache clusters are only accessible from EC2 instances. You cannot make calls to your Redis cluster from the outside. This means if you have created a Redis cluster and are trying to access it from your local computer, you won’t be able to do it. Anyhow, for development purposes you may need to access your Redis cluster from your development machine, for which you can follow this guide which explains the additional steps.
[Step #2: Creating Elasticache Instance]
While creating your new Elasticache cluster, please keep the following points in mind:
1. Cluster engine should be set to Redis.
2. You can enable cluster mode if you want to, but as this tutorial only covers the basic usage, so we keep it disabled.
3. You need to give a unique name to your Redis cluster. We have named it ‘eduonix-rc’ for this example.
4. ‘Number of replicas’ is set to None.
5. Port is set to the default i.e. 6379.
6. Node type is changed to ‘cache.t2.micro’ for this example.
7. Make sure that the ‘security group’ is set only to the one created above i.e. ‘eduonix-sg’.
8. Everything else can be left to the ‘default value’.
[Step #3 Creating EC2 Instance]
For this example, we will create a 64-bit ‘Ubuntu Server 16.04 LTS (HVM)’ instance. While creating this instance, at “Step 6: Configure Security Group”, make sure to assign the security group to the one created in the first step i.e. ‘eduonix-sg’. All other options can be set as per your preference.
[Step #4 Setting up EC2 instance to access Redis cluster]
Once the instance is launched. you need to access this instance via SSH using your ‘.pem’ file. Sample command is as follows:
1$ pranav@pranav-laptop:~/Desktop$ ssh -i ./[keys.pem] ubuntu@ec2-[ip-address].ap-south-1.compute.amazonaws.com
Once you are logged in to your ec2 instance, the first thing that you need to do is install the ‘redis tools’, we will use this tool to check the connection with our Redis cluster. You can install the ‘Redis tools’ with the following terminal commands:
$ sudo apt-get update
$ sudo apt-get install redis-tools
Once done, we now use the following terminal command to access our newly created Redis cluster:
$ redis-cli -h [Primary-endpoint-url-of-the-cluster] -p 6379
Using the above command, you should now enter the Redis CLI mode. Try the following two commands to check your Redis installation:
$ set name "Michael Jackson"
$ get name
If everything has been properly configured, the above commands should get and set values without any problems.
The next requirement is to install PHP. You can either install the entire LAMP Stack or just PHP CLI. For this example, we will only install PHP for this example using the following command:
$ sudo apt-get install php7.0-cli
Once done, we can check our PHP installation using the following command:-
$ php -v
The above command should print the basic PHP information on the terminal. We are now all set to access our Redis cluster from our EC2 instance using PHP.
Please note: – The following code examples will work in both CLI mode and server side mode.
[Step #5 Installing Predis library to use with our PHP code]
Redis has bindings for almost all mainstream programming languages. The complete list of PHP bindings for Redis can be found here. For this example, we will be using PHP Predislibrary. This lbrary is mature and stable and is being widely used by the PHP community. The complete list of available functionality for this library can be found here. You can directly download this library from Github and use it in your PHP code or you can use Composer package manager to install this library. In this example, we will be installing Predis using Composer. The Composer command to install Predis is as follows:
$ sudo apt-get install zip unzip
$ composer require predis/predis
Here, we are installing the official Predis pakage from Packagist. ‘Zip’ and ‘Unzip’ packages are required by Composer, so we are installing these packages before running the composer command.
[Step #6 Preparing PHP code to access Redis cluster]
We are now ready to access our Redis cluster using PHP. Please have a look at the following PHP code:
require __DIR__.'/vendor/autoload.php'; # including composer autoload file
# making redis connection
try{
$redis = new Predis\Client([
'scheme' => 'tcp',
'host' => '[Primary-endpoint-url-of-the-redis-cluster]',
'port' => 6379
]);
}catch(Exception $ex){
echo $ex->getMessage();
}
# working with simple string values
$redis->set("hello_world", "Hello Redis from php!");
echo $redis->get("hello_world");
?>
The above code once executed should print “Hello Redis from php!” on the screen. Make sure to replace “[Primary-endpoint-url-of-the-redis-cluster]” with the endpoint of your Redis cluster (this endpoint url can be found in your AWS Console).
[Data types supported in Redis]
Now you have your Redis cluster up and running on AWS. You can perform all supported Read/Write operations on this cluster that you would on any other Redis server. Data types that are supported by Redis are as follows:
1. Strings
2. Lists
3. Sets
4. Hashes
5. Sorted sets
6. Bitmaps and HyperLogLogs
More on these can be found at the official Redis documenation.
In the following examples, we cover the two most commonly used data types in Redis, i.e. strings and hashes. Strings can be simple strings as well as numbers. Numbers are treated as strings in Redis. Hashes are more like JSON objects or multi dimensional PHP Arrays. Both of these data types are demonstrated below.
Read / Write operations on strings
$redis->set("hello_world", "Hi All from Predis!");
echo $redis->get("hello_world");
echo "\n";
$redis->set("my_age", 29);
echo $redis->get("my_age");
echo "\n";
?>
Please note: – Both of the above values i.e. (“Hi All from Predis!” and 29) are stored as strings in Redis. The above code would output:——————————————————————————————
Hi All from Predis!
29
—————————————————————————————
Read / Write operations on hashes
$redis->hmset("captain-america", [
'real name' => 'Steve Rogers',
'super power' => 'Super Human Strength',
'superhero name' => 'Captain America',
'age in years' => 120
]);
echo "Age of Steve Rogers is ".$redis->hget('captain-america', 'age in years')." years.\n";
echo "Complete Profile of Steve Rogers is:\n";
var_dump($redis->hgetall('captain-america'));
echo "\n";
?>
The output of the above code would be as follows:
——————————————————————————————
Age of Steve Rogers is 120 years.
Complete Profile of Steve Rogers is:
array(4) {
[“real name”]=>
string(12) “Steve Rogers”
[“super power”]=>
string(20) “Super Human Strength”
[“superhero name”]=>
string(15) “Captain America”
[“age in years”]=>
string(3) “120”
}
——————————————————————————————
Basically, You can perform all kinds of operations on the Redis cluster that you would on your stand alone Redis installation. This includes all supported data types as well as additional functions like incrementers and decrementers.