Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. This article shows how to install Redis to work with Linux-based PHP development environment.
Installation and Configuration
- Download and install Redis
[root@signals phpredis-master]# wget http://redis.googlecode.com/files/redis-2.6.11.tar.gz [root@signals phpredis-master]# tar xzf redis-2.6.11.tar.gz [root@signals phpredis-master]# cd redis-2.6.11 [root@signals phpredis-master]# make
- To have redis run as a daemon, edit redis.conf, change:
daemonize yes
- Start redis:
[root@signals phpredis-master]# src/redis-server &
- OR: create a init script for redis
- Create a new file /etc/init.d/redis-server with the following content
#!/bin/sh # # redis - this script starts and stops the redis-server daemon # # chkconfig: - 85 15 # description: Redis is a persistent key-value database # processname: redis-server # config: /etc/redis/redis.conf # config: /etc/sysconfig/redis # pidfile: /var/run/redis.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 redis="/usr/local/src/redis-2.6.11/src/redis-server" prog=$(basename $redis) REDIS_CONF_FILE="/usr/local/src/redis-2.6.11/redis.conf" [ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis lockfile=/var/lock/subsys/redis start() { [ -x $redis ] || exit 5 [ -f $REDIS_CONF_FILE ] || exit 6 echo -n $"Starting $prog: " daemon $redis $REDIS_CONF_FILE retval=$? echo [ $retval -eq 0 ] && touch $lockfile return $retval } stop() { echo -n $"Stopping $prog: " killproc $prog -QUIT retval=$? echo [ $retval -eq 0 ] && rm -f $lockfile return $retval } restart() { stop start } reload() { echo -n $"Reloading $prog: " killproc $redis -HUP RETVAL=$? echo } force_reload() { restart } rh_status() { status $prog } rh_status_q() { rh_status >/dev/null 2>&1 } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart|configtest) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" exit 2 esac
- Set permission to execute it:
[tienlv@localhost src]$ chmod +x /etc/init.d/redis-server
- Enable redis-server at startup:
chkconfig redis-server on
- Start/stop/restart the redis with
/etc/init.d/redis-server stop|start|restart
- Create a new file /etc/init.d/redis-server with the following content
- Install Redis php
[root@signals phpredis-master]# wget https://github.com/owlient/phpredis/archive/master.zip [root@signals phpredis-master]# mv master php-redis-master.zip [root@signals phpredis-master]# unzip php-redis-master.zip [root@signals phpredis-master]# cd phpredis-master [root@signals phpredis-master]# phpize [root@signals phpredis-master]# ./configure [root@signals phpredis-master]# make && make install
- If you still do not see redis with phpinfo(), check where is the conf.d of php, and then add a new file: redis.ini with the following content
;configure the redis module extension=redis.so
- To check if php redis is installed properly, create a new php file containing the following line:
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379);//default port ?>
Basic Usage
SET, GET, and EXISTS
The most important commands used with Redis are SET
, GET
, and EXISTS
. You can use these commands to store and check on temporary information that is going to be accessed multiple times, typically in a key/value manner. For example:
<?php $redis->set("hello_world", "Hi from php!"); $value = $redis->get("hello_world"); var_dump($value); echo ($redis->exists("Santa Claus")) ? "true" : "false";
The set()
method is used to set a value to a particular key, in this case the key is “hello_world” and the value is “Hi from php!” The get()
method retrieves the value for the key, again in this case “hello_world”. The exists()
method reports back whether the provided key is found or not in Redis’ storage.
The key is not restricted to alphanumeric characters and the underscore. The following will work just as well:
<?php $redis->set("I 2 love Php!", "Also Redis now!"); $value = $redis->get("I 2 love Php!");
INCR (INCRBY) and DECR (DECRBY)
The INCR
and DECR
commands are used to increment and decrement values and are a great way to maintain counters. INCR and DECR increment/decrement their values by 1; you can also use INCRBY
and DECRBY
to adjust by larger intervals. Here’s an example:
<?php // increment the number of views by 1 for an article // with id 234 $redis->incr("article_views_234"); // increment views for article 237 by 5 $redis->incrby("article_views_237", 5); // decrement views for article 237 $redis->decr("article_views_237"); // decrement views for article 237 by 3 $redis->decrby("article_views_237", 3);
Redis Data Types
As I mentioned earlier, Redis has built-in data types. You may be thinking that it’s odd to have data types in a NoSQL key-value storage system such as Redis, but this would be useful for developers to structure the information in a more meaningful way and perform specific operations which is typically much faster when the data is typed. Redis’ data types are:
- String – the basic data type used in Redis in which you can store from few characters to the content of an entire file.
- List – a simple list of strings order by the insertion of its elements. You can add and remove elements from both the list’s head and tail, so you can use this data type to implement queues.
- Hash – a map of string keys and string values. In this way you can represent objects (think of it as a one-level deep JSON object).
- Set – an unordered collection of strings where you can add, remove, and test for existence of members. The one constraint is that you are not allowed to have repeated members.
- Sorted set – a particular case of the set data type. The difference is that every member has and associated score that is used order the set from the smallest to the greatest score.
So far I’ve only demonstrated strings, but there are commands that make working with data in other data types just as easy.
HSET, HGET and HGETALL, HINCRBY, and HDEL
These commands are used to work with Redis’ hash data type:
- HSET – sets the value for a key on the the hash object.
- HGET – gets the value for a key on the hash object.
- HINCRBY – increment the value for a key of the hash object with a specified value.
- HDEL – remove a key from the object.
- HGETALL – get all keys and data for a object.
Here’s an example that demonstrates their usage:
<?php $redis->hset("taxi_car", "brand", "Toyota"); $redis->hset("taxi_car", "model", "Yaris"); $redis->hset("taxi_car", "license number", "RO-01-PHP"); $redis->hset("taxi_car", "year of fabrication", 2010); $redis->hset("taxi_car", "nr_starts", 0); /* $redis->hmset("taxi_car", array( "brand" => "Toyota", "model" => "Yaris", "license number" => "RO-01-PHP", "year of fabrication" => 2010, "nr_stats" => 0) ); */ echo "License number: " . $redis->hget("taxi_car", "license number") . "<br>"; // remove license number $redis->hdel("taxi_car", "license number"); // increment number of starts $redis->hincrby("taxi_car", "nr_starts", 1); $taxi_car = $redis->hgetall("taxi_car"); echo "All info about taxi car"; echo "<pre>"; var_dump($taxi_car); echo "</pre>";
LPUSH, RPUSH, LPOP, RPOP, LLEN, LRANGE
These are the important commands for working with the list type in Redis. A Redis list is similar to an array in PHP, and offer a great support for implementing queues, stacks, or a capped collection of a certain number of elements.
- LPUSH – prepends element(s) to a list.
- RPUSH – appends element(s) to a list.
- LPOP – removes and retrieves the first element of a list.
- RPOP – removes and retrieves the last element of a list.
- LLEN – gets the length of a list.
- LRANGE – gets elements from a list.
<?php $list = "PHP Frameworks List"; $redis->rpush($list, "Symfony 2"); $redis->rpush($list, "Symfony 1.4"); $redis->lpush($list, "Zend Framework"); echo "Number of frameworks in list: " . $redis->llen($list) . "<br>"; $arList = $redis->lrange($list, 0, -1); echo "<pre>"; print_r($arList); echo "</pre>"; // the last entry in the list echo $redis->rpop($list) . "<br>"; // the first entry in the list echo $redis->lpop($list) . "<br>";
EXPIRE , EXPIREAT , TTL, and PERSIST
Most likely, when you set a key you don’t want it to be saved forever because after a certain period of time it’s not likely to be relevant anymore. You’ll need to update its value or delete it to reduce memory usage for better performance. Redis offers four commands that let you handle data persistence easily.
- EXPIRE – sets an expiration timeout (in seconds) for a key after which it and its value will be deleted.
- EXPIREAT – sets and expiration time using a unix timestamp that represents when the key and value will be deleted.
- TTL – gets the remaining time left to live for a key with an expiration.
- PERSIST – removes the expiration on the given key.
<?php // set the expiration for next week $redis->set("expire in 1 week", "I have data for a week"); $redis->expireat("expire in 1 week", strtotime("+1 week")); $ttl = $redis->ttl("expire in 1 week"); // will be 604800 seconds // set the expiration for one hour $redis->set("expire in 1 hour", "I have data for an hour"); $redis->expire("expire in 1 hour", 3600); $ttl = $redis->ttl("expire in 1 hour"); // will be 3600 seconds // never expires $redis->set("never expire", "I want to leave forever!");
Use phpRedisAdmin to manage redis servers
- Get it:
wget https://github.com/ErikDubbelboer/phpRedisAdmin/archive/master.zip unzip master rm -fr master mv phpRedisAdmin-master phpRedisAdmin cd phpRedisAdmin
- Edit its config in include/config.php file.
- Get predis lib for its operations:
cd predis/ wget https://github.com/nrk/predis/archive/v0.8.zip unzip v0.8 rm -fr v0.8 mv predis-0.8/* ./ mv predis-0.8/.travis.yml ./ mv predis-0.8/.gitignore ./ rm -fr predis-0.8
- For secure access:
- Create .htpasswd file (use http://www.4webhelp.net/us/password.php to generate password, or use htpasswd tool)
- Create .htaccess file:
AuthUserFile /full/path/to/.htpasswd AuthType Basic AuthName "My Redis Admin server" Require valid-user
Summary
Indeed Redis has much more to offer than just being a Memcache replacement.
Redis is here for the long run; it has a growing community, support for all major languages, and offers durability and high-availability with master-slave replication. Redit is open source, so if you’re a C guru then you can fork its source code from GitHub and become a contributor.
If you’re looking for more information beyond the project site, you might want to consider checking out two great Redis books, Redis Cookbook and Redis: The Definitive Guide.