This tutorial is out of date and no longer maintained.
Redis created by Salvatore Sanfilippo is an open-source, in-memory data structure server with advanced key-value cache and store, often referred to as a NoSQL database. It is also referred to as a data structure server since it can store strings, hashes, lists, sets, sorted sets, and more.
The essence of a key-value store is the ability to store some data, called a value inside a key. This data can later be retrieved only if we know the exact key used to store it.
Salvatore Sanfilippo (creator of Redis) said Redis can be used to replace an RDBMS database. Now, although nothing is impossible, I think it would be a bad idea because using a key-value store for things, like a full-text search, might be painful. Especially, when you consider ACID compliance and syncing data in a key-value store: painful.
Below are just a few uses of Redis, though there are many more than this.
This article’s aim is not to show you the syntax of Redis (you can learn about Redis’s syntax here), in this article, we will learn how to use Redis in PHP.
Redis is pretty easy to install and the instructions, included, are for both Windows and Linux users.
To install Redis on Linux, is pretty simple, but you’ll need TCL installed if you don’t have TCL installed. You can simply run:
- sudo apt-get install tcl
To install Redis:
- wget http://download.redis.io/releases/redis-2.8.19.tar.gz
- tar xzf redis-2.8.19.tar.gz
- cd redis-2.8.19
- make
Note: 2.8.19
should be replaced with the latest stable version of Redis.
All Redis binaries are saved in the src
Folder. To start the server:
- src/redis-server
Redis installation on Windows is very easy, just visit this link, download a package, and install.
Predis is a Redis Client for PHP. It is well written and has a lot of support from the community. To use Predis just clone the repository into your working directory:
- git clone git://github.com/nrk/predis.git
First, we’ll require the Redis Autoloader and register it. Then we’ll wrap the client in a try-catch block. The connection setting for connecting to Redis on a local server is different from connecting to a remote server.
<?php
require "predis/autoload.php";
PredisAutoloader::register();
try {
$redis = new PredisClient();
// This connection is for a remote server
/*
$redis = new PredisClient(array(
"scheme" => "tcp",
"host" => "153.202.124.2",
"port" => 6379
));
*/
}
catch (Exception $e) {
die($e->getMessage());
}
Now that we have successfully connected to the Redis server, let’s start using Redis.
Redis supports a range of datatypes and you might wonder what a NoSQL key-value store has to do with datatypes? Well, these datatypes help developers store data in a meaningful way and can make data retrieval faster. Here are some of the datatypes supported by Redis:
Others are bitmaps and hyperloglogs, but they will not be discussed in this article, as they are pretty dense.
In Redis, the most important commands are SET
, GET
and EXISTS
. These commands are used to store, check, and retrieve data from a Redis server. Just like the commands, the Predis class can be used to perform Redis operations by methods with the same name as commands. For example:
<?php
// sets message to contain "Hello world"
$redis->set(';message';, ';Hello world';);
// gets the value of message
$value = $redis->get('message');
// Hello world
print($value);
echo ($redis->exists('message')) ? "Oui" : "please populate the message key";
INCR
and DECR
are commands used to either decrease or increase a value.
<?php
$redis->set("counter", 0);
$redis->incr("counter"); // 1
$redis->incr("counter"); // 2
$redis->decr("counter"); // 1
We can also increase the values of the counter key by larger integer values or we can decrease the value of the counter key with the INCRBY
and DECRBY
commands.
<?php
$redis->set("counter", 0);
$redis->incrby("counter", 15); // 15
$redis->incrby("counter", 5); // 20
$redis->decrby("counter", 10); // 10
There are a few basic Redis commands for working with lists and they are:
Simple List Usage:
<?php
$redis->rpush("languages", "french"); // [french]
$redis->rpush("languages", "arabic"); // [french, arabic]
$redis->lpush("languages", "english"); // [english, french, arabic]
$redis->lpush("languages", "swedish"); // [swedish, english, french, arabic]
$redis->lpop("languages"); // [english, french, arabic]
$redis->rpop("languages"); // [english, french]
$redis->llen("languages"); // 2
$redis->lrange("languages", 0, -1); // returns all elements
$redis->lrange("languages", 0, 1); // [english, french]
A hash in Redis is a map between one string field and string values, like a one-to-many relationship. The commands associated with hashes in Redis are:
<?php
$key = ';linus torvalds';;
$redis->hset($key, ';age';, 44);
$redis->hset($key, ';country';, ';finland';);
$redis->hset($key, 'occupation', 'software engineer');
$redis->hset($key, 'reknown', 'linux kernel');
$redis->hset($key, 'to delete', 'i will be deleted');
$redis->get($key, 'age'); // 44
$redis->get($key, 'country')); // Finland
$redis->del($key, 'to delete');
$redis->hincrby($key, 'age', 20); // 64
$redis->hmset($key, [
'age' => 44,
'country' => 'finland',
'occupation' => 'software engineer',
'reknown' => 'linux kernel',
]);
// finally
$data = $redis->hgetall($key);
print_r($data); // returns all key-value that belongs to the hash
/*
[
'age' => 44,
'country' => 'finland',
'occupation' => 'software engineer',
'reknown' => 'linux kernel',
]
*/
The list of commands associated with sets includes:
<?php
$key = "countries";
$redis->sadd($key, ';china';);
$redis->sadd($key, ['england', 'france', 'germany']);
$redis->sadd($key, 'china'); // this entry is ignored
$redis->srem($key, ['england', 'china']);
$redis->sismember($key, 'england'); // false
$redis->smembers($key); // ['france', 'germany']
Since Redis is an in-memory data store, you would probably not store data forever. Therefore, this brings us to EXPIRE
, EXPIREAT
, TTL
, PERSIST
:
$key = "expire in 1 hour";
$redis->expire($key, 3600); // expires in 1 hour
$redis->expireat($key, time() + 3600); // expires in 1 hour
sleep(600); // don't try this, just an illustration for time spent
$redis->ttl($key); // 3000, ergo expires in 50 minutes
$redis->persist($key); // this will never expire.
The commands listed in this article are just a handful of many existing Redis commands (see more redis commands).
Redis is a better replacement for memcached, as it is faster, scales better (supports master-slave replication), supports datatypes that many (Facebook, Twitter, Instagram) have dropped memcached for Redis. Redis is open source and many brilliant programmers from the open-source community have contributed patches.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!