Redis - Quick Guide

Redis is an open source, advanced key-value store and an apt solution for building highperformance, scalable web applications.
Redis has three main peculiarities that sets it apart.
Redis holds its database entirely in the memory, using the disk only for persistence.
Redis holds its database entirely in the memory, using the disk only for persistence.
Redis has a relatively rich set of data types when compared to many key-value data stores.
Redis has a relatively rich set of data types when compared to many key-value data stores.
Redis can replicate data to any number of slaves.
Redis can replicate data to any number of slaves.
Following are certain advantages of Redis.
Exceptionally fast − Redis is very fast and can perform about 110000 SETs per second, about 81000 GETs per second.
Exceptionally fast − Redis is very fast and can perform about 110000 SETs per second, about 81000 GETs per second.
Supports rich data types − Redis natively supports most of the datatypes that developers already know such as list, set, sorted set, and hashes. This makes it easy to solve a variety of problems as we know which problem can be handled better by which data type.
Supports rich data types − Redis natively supports most of the datatypes that developers already know such as list, set, sorted set, and hashes. This makes it easy to solve a variety of problems as we know which problem can be handled better by which data type.
Operations are atomic − All Redis operations are atomic, which ensures that if two clients concurrently access, Redis server will receive the updated value.
Operations are atomic − All Redis operations are atomic, which ensures that if two clients concurrently access, Redis server will receive the updated value.
Multi-utility tool − Redis is a multi-utility tool and can be used in a number of use cases such as caching, messaging-queues (Redis natively supports Publish/Subscribe), any short-lived data in your application, such as web application sessions, web page hit counts, etc.
Multi-utility tool − Redis is a multi-utility tool and can be used in a number of use cases such as caching, messaging-queues (Redis natively supports Publish/Subscribe), any short-lived data in your application, such as web application sessions, web page hit counts, etc.
Redis is a different evolution path in the key-value DBs, where values can contain more complex data types, with atomic operations defined on those data types.
Redis is a different evolution path in the key-value DBs, where values can contain more complex data types, with atomic operations defined on those data types.
Redis is an in-memory database but persistent on disk database, hence it represents a different trade off where very high write and read speed is achieved with the limitation of data sets that can't be larger than the memory.
Redis is an in-memory database but persistent on disk database, hence it represents a different trade off where very high write and read speed is achieved with the limitation of data sets that can't be larger than the memory.
Another advantage of in-memory databases is that the memory representation of complex data structures is much simpler to manipulate compared to the same data structure on disk. Thus, Redis can do a lot with little internal complexity.
Another advantage of in-memory databases is that the memory representation of complex data structures is much simpler to manipulate compared to the same data structure on disk. Thus, Redis can do a lot with little internal complexity.
In this chapter, you will learn about the environmental setup for Redis.
To install Redis on Ubuntu, go to the terminal and type the following commands −
$sudo apt-get update 
$sudo apt-get install redis-server

This will install Redis on your machine.
$redis-server

$redis-cli 

This will open a redis prompt.
redis 127.0.0.1:6379>

In the above prompt, 127.0.0.1 is your machine's IP address and 6379 is the port on which Redis server is running. Now type the following PING command.
redis 127.0.0.1:6379> ping 
PONG

This shows that Redis is successfully installed on your machine.
To install Redis desktop manager on Ubuntu, just download the package from https://redisdesktop.com/download
Open the downloaded package and install it.
Redis desktop manager will give you UI to manage your Redis keys and data.
In Redis, there is a configuration file (redis.conf) available at the root directory of Redis. Although you can get and set all Redis configurations by Redis CONFIG command.
Following is the basic syntax of Redis CONFIG command.
redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME

redis 127.0.0.1:6379> CONFIG GET loglevel  
1) "loglevel" 
2) "notice"

To get all configuration settings, use * in place of CONFIG_SETTING_NAME
redis 127.0.0.1:6379> CONFIG GET *  
  1) "dbfilename" 
  2) "dump.rdb" 
  3) "requirepass" 
  4) "" 
  5) "masterauth" 
  6) "" 
  7) "unixsocket" 
  8) "" 
  9) "logfile" 
 10) "" 
 11) "pidfile" 
 12) "/var/run/redis.pid" 
 13) "maxmemory" 
 14) "0"
 15) "maxmemory-samples" 
 16) "3" 
 17) "timeout" 
 18) "0" 
 19) "tcp-keepalive" 
 20) "0" 
 21) "auto-aof-rewrite-percentage" 
 22) "100" 
 23) "auto-aof-rewrite-min-size" 
 24) "67108864" 
 25) "hash-max-ziplist-entries" 
 26) "512" 
 27) "hash-max-ziplist-value" 
 28) "64" 
 29) "list-max-ziplist-entries" 
 30) "512" 
 31) "list-max-ziplist-value" 
 32) "64" 
 33) "set-max-intset-entries" 
 34) "512" 
 35) "zset-max-ziplist-entries" 
 36) "128" 
 37) "zset-max-ziplist-value" 
 38) "64" 
 39) "hll-sparse-max-bytes" 
 40) "3000" 
 41) "lua-time-limit" 
 42) "5000" 
 43) "slowlog-log-slower-than" 
 44) "10000" 
 45) "latency-monitor-threshold" 
 46) "0" 
 47) "slowlog-max-len" 
 48) "128" 
 49) "port" 
 50) "6379" 
 51) "tcp-backlog" 
 52) "511" 
 53) "databases" 
 54) "16" 
 55) "repl-ping-slave-period" 
 56) "10" 
 57) "repl-timeout" 
 58) "60" 
 59) "repl-backlog-size" 
 60) "1048576" 
 61) "repl-backlog-ttl" 
 62) "3600" 
 63) "maxclients" 
 64) "4064" 
 65) "watchdog-period" 
 66) "0" 
 67) "slave-priority" 
 68) "100" 
 69) "min-slaves-to-write" 
 70) "0" 
 71) "min-slaves-max-lag" 
 72) "10" 
 73) "hz" 
 74) "10" 
 75) "no-appendfsync-on-rewrite" 
 76) "no" 
 77) "slave-serve-stale-data" 
 78) "yes" 
 79) "slave-read-only" 
 80) "yes" 
 81) "stop-writes-on-bgsave-error" 
 82) "yes" 
 83) "daemonize" 
 84) "no" 
 85) "rdbcompression" 
 86) "yes"
 87) "rdbchecksum" 
 88) "yes" 
 89) "activerehashing" 
 90) "yes" 
 91) "repl-disable-tcp-nodelay" 
 92) "no" 
 93) "aof-rewrite-incremental-fsync" 
 94) "yes" 
 95) "appendonly" 
 96) "no" 
 97) "dir" 
 98) "/home/deepak/Downloads/redis-2.8.13/src" 
 99) "maxmemory-policy" 
100) "volatile-lru" 
101) "appendfsync" 
102) "everysec" 
103) "save" 
104) "3600 1 300 100 60 10000" 
105) "loglevel" 
106) "notice" 
107) "client-output-buffer-limit" 
108) "normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60" 
109) "unixsocketperm" 
110) "0" 
111) "slaveof" 
112) "" 
113) "notify-keyspace-events" 
114) "" 
115) "bind" 
116) "" 

To update configuration, you can edit redis.conf file directly or you can update configurations via CONFIG set command.
Following is the basic syntax of CONFIG SET command.
redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE

redis 127.0.0.1:6379> CONFIG SET loglevel "notice" 
OK 
redis 127.0.0.1:6379> CONFIG GET loglevel  
1) "loglevel" 
2) "notice" 

Redis supports 5 types of data types.
Redis string is a sequence of bytes. Strings in Redis are binary safe, meaning they have a known length not determined by any special terminating characters. Thus, you can store anything up to 512 megabytes in one string.
redis 127.0.0.1:6379> SET name "tutorialspoint" 
OK 
redis 127.0.0.1:6379> GET name 
"tutorialspoint"

In the above example, SET and GET are Redis commands, name is the key used in Redis and tutorialspoint is the string value that is stored in Redis.
Note − A string value can be at max 512 megabytes in length.
A Redis hash is a collection of key value pairs. Redis Hashes are maps between string fields and string values. Hence, they are used to represent objects.
redis 127.0.0.1:6379> HMSET user:1 username tutorialspoint password 
tutorialspoint points 200 
OK 
redis 127.0.0.1:6379> HGETALL user:1  
1) "username" 
2) "tutorialspoint" 
3) "password" 
4) "tutorialspoint" 
5) "points" 
6) "200"

In the above example, hash data type is used to store the user's object which contains basic information of the user. Here HMSET, HGETALL are commands for Redis, while user − 1 is the key.
Every hash can store up to 232 - 1 field-value pairs (more than 4 billion).
Redis Lists are simply lists of strings, sorted by insertion order. You can add elements to a Redis List on the head or on the tail.
redis 127.0.0.1:6379> lpush tutoriallist redis 
(integer) 1 
redis 127.0.0.1:6379> lpush tutoriallist mongodb 
(integer) 2 
redis 127.0.0.1:6379> lpush tutoriallist rabitmq 
(integer) 3 
redis 127.0.0.1:6379> lrange tutoriallist 0 10  

1) "rabitmq" 
2) "mongodb" 
3) "redis"

The max length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per list).
Redis Sets are an unordered collection of strings. In Redis, you can add, remove, and test for the existence of members in O(1) time complexity.
redis 127.0.0.1:6379> sadd tutoriallist redis 
(integer) 1 
redis 127.0.0.1:6379> sadd tutoriallist mongodb 
(integer) 1 
redis 127.0.0.1:6379> sadd tutoriallist rabitmq 
(integer) 1 
redis 127.0.0.1:6379> sadd tutoriallist rabitmq 
(integer) 0 
redis 127.0.0.1:6379> smembers tutoriallist  

1) "rabitmq" 
2) "mongodb" 
3) "redis" 

Note − In the above example, rabitmq is added twice, however due to unique property of the set, it is added only once.
The max number of members in a set is 232 - 1 (4294967295, more than 4 billion of members per set).
Redis Sorted Sets are similar to Redis Sets, non-repeating collections of Strings. The difference is, every member of a Sorted Set is associated with a score, that is used in order to take the sorted set ordered, from the smallest to the greatest score. While members are unique, the scores may be repeated.
redis 127.0.0.1:6379> zadd tutoriallist 0 redis 
(integer) 1 
redis 127.0.0.1:6379> zadd tutoriallist 0 mongodb 
(integer) 1 
redis 127.0.0.1:6379> zadd tutoriallist 0 rabitmq 
(integer) 1 
redis 127.0.0.1:6379> zadd tutoriallist 0 rabitmq 
(integer) 0 
redis 127.0.0.1:6379> ZRANGEBYSCORE tutoriallist 0 1000  

1) "redis" 
2) "mongodb" 
3) "rabitmq" 

Redis commands are used to perform some operations on Redis server.
To run commands on Redis server, you need a Redis client. Redis client is available in Redis package, which we have installed earlier.
Following is the basic syntax of Redis client.
$redis-cli 

Following example explains how we can start Redis client.
To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command.
$redis-cli 
redis 127.0.0.1:6379> 
redis 127.0.0.1:6379> PING  
PONG

In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.
To run commands on Redis remote server, you need to connect to the server by the same client redis-cli
$ redis-cli -h host -p port -a password

Following example shows how to connect to Redis remote server, running on host 127.0.0.1, port 6379 and has password mypass.
$redis-cli -h 127.0.0.1 -p 6379 -a "mypass" 
redis 127.0.0.1:6379> 
redis 127.0.0.1:6379> PING  
PONG

Redis keys commands are used for managing keys in Redis. Following is the syntax for using redis keys commands.
redis 127.0.0.1:6379> COMMAND KEY_NAME

redis 127.0.0.1:6379> SET tutorialspoint redis 
OK 
redis 127.0.0.1:6379> DEL tutorialspoint 
(integer) 1

In the above example, DEL is the command, while tutorialspoint is the key. If the key is deleted, then the output of the command will be (integer) 1, otherwise it will be (integer) 0.
Following table lists some basic commands related to keys.
This command deletes the key, if it exists.
This command returns a serialized version of the value stored at the specified key.
This command checks whether the key exists or not.
Sets the expiry of the key after the specified time.
Sets the expiry of the key after the specified time. Here time is in Unix timestamp format.
Set the expiry of key in milliseconds.
Sets the expiry of the key in Unix timestamp specified as milliseconds.
Finds all keys matching the specified pattern.
Moves a key to another database.
Removes the expiration from the key.
Gets the remaining time in keys expiry in milliseconds.
Gets the remaining time in keys expiry.
Returns a random key from Redis.
Changes the key name.
Renames the key, if a new key doesn't exist.
Returns the data type of the value stored in the key.
Redis strings commands are used for managing string values in Redis. Following is the syntax for using Redis string commands.
redis 127.0.0.1:6379> COMMAND KEY_NAME 

redis 127.0.0.1:6379> SET tutorialspoint redis 
OK 
redis 127.0.0.1:6379> GET tutorialspoint 
"redis" 

In the above example, SET and GET are the commands, while tutorialspoint is the key.
Following table lists some basic commands to manage strings in Redis.
This command sets the value at the specified key.
Gets the value of a key.
Gets a substring of the string stored at a key.
Sets the string value of a key and return its old value.
Returns the bit value at the offset in the string value stored at the key.
Gets the values of all the given keys
Sets or clears the bit at the offset in the string value stored at the key
Sets the value with the expiry of a key
Sets the value of a key, only if the key does not exist
Overwrites the part of a string at the key starting at the specified offset
Gets the length of the value stored in a key
Sets multiple keys to multiple values
Sets multiple keys to multiple values, only if none of the keys exist
Sets the value and expiration in milliseconds of a key
Increments the integer value of a key by one
Increments the integer value of a key by the given amount
Increments the float value of a key by the given amount
Decrements the integer value of a key by one
Decrements the integer value of a key by the given number
Appends a value to a key
Redis Hashes are maps between the string fields and the string values. Hence, they are the perfect data type to represent objects.
In Redis, every hash can store up to more than 4 billion field-value pairs.
redis 127.0.0.1:6379> HMSET tutorialspoint name "redis tutorial" 
description "redis basic commands for caching" likes 20 visitors 23000 
OK 
redis 127.0.0.1:6379> HGETALL tutorialspoint  
1) "name" 
2) "redis tutorial" 
3) "description" 
4) "redis basic commands for caching" 
5) "likes" 
6) "20" 
7) "visitors" 
8) "23000"

In the above example, we have set Redis tutorials detail (name, description, likes, visitors) in hash named ‘tutorialspoint’.
Following table lists some basic commands related to hash.
Deletes one or more hash fields.
Determines whether a hash field exists or not.
Gets the value of a hash field stored at the specified key.
Gets all the fields and values stored in a hash at the specified key
Increments the integer value of a hash field by the given number
Increments the float value of a hash field by the given amount
Gets all the fields in a hash
Gets the number of fields in a hash
Gets the values of all the given hash fields
Sets multiple hash fields to multiple values
Sets the string value of a hash field
Sets the value of a hash field, only if the field does not exist
Gets all the values in a hash
Incrementally iterates hash fields and associated values
Redis Lists are simply lists of strings, sorted by insertion order. You can add elements in Redis lists in the head or the tail of the list.
Maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per list).
redis 127.0.0.1:6379> LPUSH tutorials redis 
(integer) 1 
redis 127.0.0.1:6379> LPUSH tutorials mongodb 
(integer) 2 
redis 127.0.0.1:6379> LPUSH tutorials mysql 
(integer) 3 
redis 127.0.0.1:6379> LRANGE tutorials 0 10  
1) "mysql" 
2) "mongodb" 
3) "redis"

In the above example, three values are inserted in Redis list named ‘tutorials’ by the command LPUSH.
Following table lists some basic commands related to lists.
Removes and gets the first element in a list, or blocks until one is available
Removes and gets the last element in a list, or blocks until one is available
Pops a value from a list, pushes it to another list and returns it; or blocks until one is available
Gets an element from a list by its index
Inserts an element before or after another element in a list
Gets the length of a list
Removes and gets the first element in a list
Prepends one or multiple values to a list
Prepends a value to a list, only if the list exists
Gets a range of elements from a list
Removes elements from a list
Sets the value of an element in a list by its index
Trims a list to the specified range
Removes and gets the last element in a list
Removes the last element in a list, appends it to another list and returns it
Appends one or multiple values to a list
Appends a value to a list, only if the list exists
Redis Sets are an unordered collection of unique strings. Unique means sets does not allow repetition of data in a key.
In Redis set add, remove, and test for the existence of members in O(1) (constant time regardless of the number of elements contained inside the Set). The maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per set).
redis 127.0.0.1:6379> SADD tutorials redis 
(integer) 1 
redis 127.0.0.1:6379> SADD tutorials mongodb 
(integer) 1 
redis 127.0.0.1:6379> SADD tutorials mysql 
(integer) 1 
redis 127.0.0.1:6379> SADD tutorials mysql 
(integer) 0 
redis 127.0.0.1:6379> SMEMBERS tutorials  
1) "mysql" 
2) "mongodb" 
3) "redis"

In the above example, three values are inserted in Redis set named ‘tutorials’ by the command SADD.
Following table lists some basic commands related to sets.
Adds one or more members to a set
Gets the number of members in a set
Subtracts multiple sets
Subtracts multiple sets and stores the resulting set in a key
Intersects multiple sets
Intersects multiple sets and stores the resulting set in a key
Determines if a given value is a member of a set
Gets all the members in a set
Moves a member from one set to another
Removes and returns a random member from a set
Gets one or multiple random members from a set
Removes one or more members from a set
Adds multiple sets
Adds multiple sets and stores the resulting set in a key
Incrementally iterates set elements
Redis Sorted Sets are similar to Redis Sets with the unique feature of values stored in a set. The difference is, every member of a Sorted Set is associated with a score, that is used in order to take the sorted set ordered, from the smallest to the greatest score.
In Redis sorted set, add, remove, and test for the existence of members in O(1) (constant time regardless of the number of elements contained inside the set). Maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per set).
redis 127.0.0.1:6379> ZADD tutorials 1 redis 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 2 mongodb 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 3 mysql 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 3 mysql 
(integer) 0 
redis 127.0.0.1:6379> ZADD tutorials 4 mysql 
(integer) 0 
redis 127.0.0.1:6379> ZRANGE tutorials 0 10 WITHSCORES  
1) "redis" 
2) "1" 
3) "mongodb" 
4) "2" 
5) "mysql" 
6) "4" 

In the above example, three values are inserted with its score in Redis sorted set named ‘tutorials’ by the command ZADD.
Following table lists some basic commands related to sorted sets.
Adds one or more members to a sorted set, or updates its score, if it already exists
Gets the number of members in a sorted set
Counts the members in a sorted set with scores within the given values
Increments the score of a member in a sorted set
Intersects multiple sorted sets and stores the resulting sorted set in a new key
Counts the number of members in a sorted set between a given lexicographical range
Returns a range of members in a sorted set, by index
Returns a range of members in a sorted set, by lexicographical range
Returns a range of members in a sorted set, by score
Determines the index of a member in a sorted set
Removes one or more members from a sorted set
Removes all members in a sorted set between the given lexicographical range
Removes all members in a sorted set within the given indexes
Removes all members in a sorted set within the given scores
Returns a range of members in a sorted set, by index, with scores ordered from high to low
Returns a range of members in a sorted set, by score, with scores ordered from high to low
Determines the index of a member in a sorted set, with scores ordered from high to low
Gets the score associated with the given member in a sorted set
Adds multiple sorted sets and stores the resulting sorted set in a new key
Incrementally iterates sorted sets elements and associated scores
Redis HyperLogLog is an algorithm that uses randomization in order to provide an approximation of the number of unique elements in a set using just a constant, and small amount of memory.
HyperLogLog provides a very good approximation of the cardinality of a set even using a very small amount of memory around 12 kbytes per key with a standard error of 0.81%. There is no limit to the number of items you can count, unless you approach 264 items.
Following example explains how Redis HyperLogLog works.
redis 127.0.0.1:6379> PFADD tutorials "redis"  
1) (integer) 1  
redis 127.0.0.1:6379> PFADD tutorials "mongodb"  
1) (integer) 1  
redis 127.0.0.1:6379> PFADD tutorials "mysql"  
1) (integer) 1  
redis 127.0.0.1:6379> PFCOUNT tutorials  
(integer) 3 

Following table lists some basic commands related to Redis HyperLogLog.
Adds the specified elements to the specified HyperLogLog.
Returns the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
Merges N different HyperLogLogs into a single one.

Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel.
In Redis, a client can subscribe any number of channels.
Following example explains how publish subscriber concept works. In the following example, one client subscribes a channel named ‘redisChat’.
redis 127.0.0.1:6379> SUBSCRIBE redisChat  
Reading messages... (press Ctrl-C to quit) 
1) "subscribe" 
2) "redisChat" 
3) (integer) 1 

Now, two clients are publishing the messages on the same channel named ‘redisChat’ and the above subscribed client is receiving messages.
redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"  
(integer) 1  
redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by tutorials point"  
(integer) 1   
1) "message" 
2) "redisChat" 
3) "Redis is a great caching technique" 
1) "message" 
2) "redisChat" 
3) "Learn redis by tutorials point" 

Following table lists some basic commands related to Redis Pub/Sub.
Subscribes to channels matching the given patterns.
Tells the state of Pub/Sub system. For example, which clients are active on the server.
Posts a message to a channel.
Stops listening for messages posted to channels matching the given patterns.
Listens for messages published to the given channels.
Stops listening for messages posted to the given channels.
Redis transactions allow the execution of a group of commands in a single step. Following are the two properties of Transactions.
All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction.
All commands in a transaction are sequentially executed as a single isolated operation. It is not possible that a request issued by another client is served in the middle of the execution of a Redis transaction.
Redis transaction is also atomic. Atomic means either all of the commands or none are processed.
Redis transaction is also atomic. Atomic means either all of the commands or none are processed.
Redis transaction is initiated by command MULTI and then you need to pass a list of commands that should be executed in the transaction, after which the entire transaction is executed by EXEC command.
redis 127.0.0.1:6379> MULTI 
OK 
List of commands here 
redis 127.0.0.1:6379> EXEC

Following example explains how Redis transaction can be initiated and executed.
redis 127.0.0.1:6379> MULTI 
OK 
redis 127.0.0.1:6379> SET tutorial redis 
QUEUED 
redis 127.0.0.1:6379> GET tutorial 
QUEUED 
redis 127.0.0.1:6379> INCR visitors 
QUEUED 
redis 127.0.0.1:6379> EXEC  
1) OK 
2) "redis" 
3) (integer) 1 

Following table shows some basic commands related to Redis transactions.
Discards all commands issued after MULTI
Executes all commands issued after MULTI
Marks the start of a transaction block
Forgets about all watched keys
Watches the given keys to determine the execution of the MULTI/EXEC block
Redis scripting is used to evaluate scripts using the Lua interpreter. It is built into Redis starting from version 2.6.0. The command used for scripting is EVAL command.
Following is the basic syntax of EVAL command.
redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]

Following example explains how Redis scripting works.
redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 
key2 first second  
1) "key1" 
2) "key2" 
3) "first" 
4) "second"

Following table lists some basic commands related to Redis Scripting.
Executes a Lua script.
Executes a Lua script.
Checks the existence of scripts in the script cache.
Removes all the scripts from the script cache.
Kills the script currently in execution.
Loads the specified Lua script into the script cache.
Redis connection commands are basically used to manage client connections with Redis server.
Following example explains how a client authenticates itself to Redis server and checks whether the server is running or not.
redis 127.0.0.1:6379> AUTH "password" 
OK 
redis 127.0.0.1:6379> PING 
PONG 

Following table lists some basic commands related to Redis connections.
Authenticates to the server with the given password
Prints the given string
Checks whether the server is running or not
Closes the current connection
Changes the selected database for the current connection
Redis server commands are basically used to manage Redis server.
Following example explains how we can get all statistics and information about the server.
redis 127.0.0.1:6379> INFO  

# Server 
redis_version:2.8.13 
redis_git_sha1:00000000 
redis_git_dirty:0 
redis_build_id:c2238b38b1edb0e2 
redis_mode:standalone 
os:Linux 3.5.0-48-generic x86_64 
arch_bits:64 
multiplexing_api:epoll 
gcc_version:4.7.2 
process_id:3856 
run_id:0e61abd297771de3fe812a3c21027732ac9f41fe 
tcp_port:6379 
uptime_in_seconds:11554 
uptime_in_days:0 hz:10 
lru_clock:16651447 
config_file:  

# Clients 
connected_clients:1
client_longest_output_list:0 
client_biggest_input_buf:0 
blocked_clients:0  

# Memory 
used_memory:589016 
used_memory_human:575.21K 
used_memory_rss:2461696 
used_memory_peak:667312 
used_memory_peak_human:651.67K 
used_memory_lua:33792 
mem_fragmentation_ratio:4.18 
mem_allocator:jemalloc-3.6.0  

# Persistence 
loading:0 
rdb_changes_since_last_save:3 
rdb_bgsave_in_progress:0 
rdb_last_save_time:1409158561 
rdb_last_bgsave_status:ok 
rdb_last_bgsave_time_sec:0 
rdb_current_bgsave_time_sec:-1 
aof_enabled:0 
aof_rewrite_in_progress:0 
aof_rewrite_scheduled:0 
aof_last_rewrite_time_sec:-1 
aof_current_rewrite_time_sec:-1 
aof_last_bgrewrite_status:ok 
aof_last_write_status:ok  

# Stats 
total_connections_received:24 
total_commands_processed:294 
instantaneous_ops_per_sec:0 
rejected_connections:0 
sync_full:0 
sync_partial_ok:0 
sync_partial_err:0 
expired_keys:0 
evicted_keys:0 
keyspace_hits:41
keyspace_misses:82 
pubsub_channels:0 
pubsub_patterns:0 
latest_fork_usec:264  

# Replication 
role:master 
connected_slaves:0 
master_repl_offset:0 
repl_backlog_active:0 
repl_backlog_size:1048576 
repl_backlog_first_byte_offset:0 
repl_backlog_histlen:0  

# CPU 
used_cpu_sys:10.49 
used_cpu_user:4.96 
used_cpu_sys_children:0.00 
used_cpu_user_children:0.01  

# Keyspace 
db0:keys = 94,expires = 1,avg_ttl = 41638810 
db1:keys = 1,expires = 0,avg_ttl = 0 
db3:keys = 1,expires = 0,avg_ttl = 0 

Following table lists some basic commands related to Redis server.
Asynchronously rewrites the append-only file
Asynchronously saves the dataset to the disk
Kills the connection of a client
Gets the list of client connections to the server
Gets the name of the current connection
Stops processing commands from the clients for a specified time
Sets the current connection name
Gets an array of Cluster slot to node mappings
Gets an array of Redis command details
Gets total number of Redis commands
Extracts the keys given a full Redis command
Asynchronously saves the dataset to the disk
Gets an array of specific Redis command details 
Gets the value of a configuration parameter
Rewrites the configuration file with the in-memory configuration
Sets a configuration parameter to the given value
Resets the stats returned by INFO
Returns the number of keys in the selected database
Gets debugging information about a key
Makes the server crash
Removes all the keys from all databases
Removes all the keys from the current database
Gets information and statistics about the server
Gets the UNIX time stamp of the last successful save to the disk
Listens for all the requests received by the server in real time
Returns the role of the instance in the context of replication
Synchronously saves the dataset to the disk
Synchronously saves the dataset to the disk and then shuts down the server
Makes the server a slave of another instance, or promotes it as a master
Manages the Redis slow queries log
Command used for replication
Returns the current server time
Redis SAVE command is used to create a backup of the current Redis database.
Following is the basic syntax of redis SAVE command.
127.0.0.1:6379> SAVE 

Following example creates a backup of the current database.
127.0.0.1:6379> SAVE  
OK 

This command will create a dump.rdb file in your Redis directory.
To restore Redis data, move Redis backup file (dump.rdb) into your Redis directory and start the server. To get your Redis directory, use CONFIG command of Redis as shown below.
127.0.0.1:6379> CONFIG get dir  
1) "dir" 
2) "/user/tutorialspoint/redis-2.8.13/src" 

In the output of the above command /user/tutorialspoint/redis-2.8.13/src is the directory, where Redis server is installed.
To create Redis backup, an alternate command BGSAVE is also available. This command will start the backup process and run this in the background.
127.0.0.1:6379> BGSAVE  
Background saving started

Redis database can be secured, such that any client making a connection needs to authenticate before executing a command. To secure Redis, you need to set the password in the config file.
Following example shows the steps to secure your Redis instance.
127.0.0.1:6379> CONFIG get requirepass 
1) "requirepass" 
2) "" 

By default, this property is blank, which means no password is set for this instance. You can change this property by executing the following command.
127.0.0.1:6379> CONFIG set requirepass "tutorialspoint" 
OK 
127.0.0.1:6379> CONFIG get requirepass 
1) "requirepass" 
2) "tutorialspoint" 

After setting the password, if any client runs the command without authentication, then (error) NOAUTH Authentication required. error will return. Hence, the client needs to use AUTH command to authenticate himself.
Following is the basic syntax of AUTH command.
127.0.0.1:6379> AUTH password 

127.0.0.1:6379> AUTH "tutorialspoint" 
OK 
127.0.0.1:6379> SET mykey "Test value" 
OK 
127.0.0.1:6379> GET mykey 
"Test value"

Redis benchmark is the utility to check the performance of Redis by running n commands simultaneously.
Following is the basic syntax of Redis benchmark.
redis-benchmark [option] [option value] 

Following example checks Redis by calling 100000 commands.
redis-benchmark -n 100000  

PING_INLINE: 141043.72 requests per second 
PING_BULK: 142857.14 requests per second 
SET: 141442.72 requests per second 
GET: 145348.83 requests per second 
INCR: 137362.64 requests per second 
LPUSH: 145348.83 requests per second 
LPOP: 146198.83 requests per second 
SADD: 146198.83 requests per second 
SPOP: 149253.73 requests per second 
LPUSH (needed to benchmark LRANGE): 148588.42 requests per second 
LRANGE_100 (first 100 elements): 58411.21 requests per second 
LRANGE_300 (first 300 elements): 21195.42 requests per second 
LRANGE_500 (first 450 elements): 14539.11 requests per second 
LRANGE_600 (first 600 elements): 10504.20 requests per second 
MSET (10 keys): 93283.58 requests per second 

Following is a list of available options in Redis benchmark.
Following example shows the multiple usage options in Redis benchmark utility.
redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 100000 -q  

SET: 146198.83 requests per second 
LPUSH: 145560.41 requests per second 

Redis accepts clients’ connections on the configured listening TCP port and on the Unix socket, if enabled. When a new client connection is accepted, the following operations are performed −
The client socket is put in non-blocking state since Redis uses multiplexing and non-blocking I/O.
The client socket is put in non-blocking state since Redis uses multiplexing and non-blocking I/O.
The TCP_NODELAY option is set in order to ensure that we don't have delays in our connection.
The TCP_NODELAY option is set in order to ensure that we don't have delays in our connection.
A readable file event is created so that Redis is able to collect the client queries as soon as new data is available to be read on the socket.
A readable file event is created so that Redis is able to collect the client queries as soon as new data is available to be read on the socket.
In Redis config (redis.conf), there is a property called maxclients, which describes the maximum number of clients that can connect to Redis.
Following is the basic syntax of command.
config get maxclients  

1) "maxclients" 
2) "10000" 

By default, this property is set to 10000 (depending upon the maximum number of file descriptors limit of OS), although you can change this property.
In the following example, we have set the maximum number of clients to 100000, while starting the server.
redis-server --maxclients 100000 

Redis is a TCP server and supports request/response protocol. In Redis, a request is accomplished with the following steps −
The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response.
The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response.
The server processes the command and sends the response back to the client.
The server processes the command and sends the response back to the client.
The basic meaning of pipelining is, the client can send multiple requests to the server without waiting for the replies at all, and finally reads the replies in a single step.
To check the Redis pipelining, just start the Redis instance and type the following command in the terminal.
$(echo -en "PING\r\n SET tutorial redis\r\nGET tutorial\r\nINCR 
visitor\r\nINCR visitor\r\nINCR visitor\r\n"; sleep 10) | nc localhost 6379  
+PONG 
+OK 
redis 
:1 
:2 
:3 

In the above example, we will check Redis connection by using PING command. We have set a string named tutorial with value redis. Later, we get that keys value and increment the visitor number three times. In the result, we can see that all commands are submitted to Redis once, and Redis provides the output of all commands in a single step.
The benefit of this technique is a drastically improved protocol performance. The speedup gained by pipelining ranges from a factor of five for connections to localhost up to a factor of at least one hundred over slower internet connections.
Partitioning is the process of splitting your data into multiple Redis instances, so that every instance will only contain a subset of your keys.
It allows for much larger databases, using the sum of the memory of many computers. Without partitioning you are limited to the amount of memory that a single computer can support.
It allows for much larger databases, using the sum of the memory of many computers. Without partitioning you are limited to the amount of memory that a single computer can support.
It allows to scale the computational power to multiple cores and multiple computers, and the network bandwidth to multiple computers and network adapters.
It allows to scale the computational power to multiple cores and multiple computers, and the network bandwidth to multiple computers and network adapters.
Operations involving multiple keys are usually not supported. For instance, you can't perform the intersection between two sets if they are stored in the keys that are mapped to different Redis instances.
Operations involving multiple keys are usually not supported. For instance, you can't perform the intersection between two sets if they are stored in the keys that are mapped to different Redis instances.
Redis transactions involving multiple keys cannot be used.
Redis transactions involving multiple keys cannot be used.
The partitioning granuliary is the key, so it is not possible to shard a dataset with a single huge key like a very big sorted set.
The partitioning granuliary is the key, so it is not possible to shard a dataset with a single huge key like a very big sorted set.
When partitioning is used, data handling is more complex. For instance, you have to handle multiple RDB/AOF files, and to get a backup of your data you need to aggregate the persistence files from multiple instances and hosts.
When partitioning is used, data handling is more complex. For instance, you have to handle multiple RDB/AOF files, and to get a backup of your data you need to aggregate the persistence files from multiple instances and hosts.
Adding and removing the capacity can be complex. For instance, Redis Cluster supports mostly transparent rebalancing of data with the ability to add and remove nodes at runtime. However, other systems like client-side partitioning and proxies don't support this feature. A technique called Presharding helps in this regard.
Adding and removing the capacity can be complex. For instance, Redis Cluster supports mostly transparent rebalancing of data with the ability to add and remove nodes at runtime. However, other systems like client-side partitioning and proxies don't support this feature. A technique called Presharding helps in this regard.
There are two types of partitioning available in Redis. Suppose we have four Redis instances, R0, R1, R2, R3 and many keys representing users like user:1, user:2, ... and so forth.
Range partitioning is accomplished by mapping ranges of objects into specific Redis instances. Suppose in our example, the users from ID 0 to ID 10000 will go into instance R0, while the users from ID 10001 to ID 20000 will go into instance R1 and so forth.
In this type of partitioning, a hash function (eg. modulus function) is used to convert the key into a number and then the data is stored in different-different Redis instances.
Before you start using Redis in your Java programs, you need to make sure that you have Redis Java driver and Java set up on the machine. You can check our Java tutorial for Java installation on your machine.
Now, let us see how to set up Redis Java driver.
You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it.
You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it.
You need to include the jedis.jar into your classpath.
You need to include the jedis.jar into your classpath.
import redis.clients.jedis.Jedis; 

public class RedisJava { 
   public static void main(String[] args) { 
      //Connecting to Redis server on localhost 
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection to server sucessfully"); 
      //check whether server is running or not 
      System.out.println("Server is running: "+jedis.ping()); 
   } 
} 
Now, let's compile and run the above program to test the connection to Redis server. You can change your path as per your requirement. We are assuming the current version of jedis.jar is available in the current path.
$javac RedisJava.java 
$java RedisJava 
Connection to server sucessfully 
Server is running: PONG

import redis.clients.jedis.Jedis; 

public class RedisStringJava { 
   public static void main(String[] args) { 
      //Connecting to Redis server on localhost 
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection to server sucessfully"); 
      //set the data in redis string 
      jedis.set("tutorial-name", "Redis tutorial"); 
      // Get the stored data and print it 
      System.out.println("Stored string in redis:: "+ jedis.get("tutorialname")); 
   } 
}
Now, let's compile and run the above program.
$javac RedisStringJava.java 
$java RedisStringJava 
Connection to server sucessfully 
Stored string in redis:: Redis tutorial 

import redis.clients.jedis.Jedis; 

public class RedisListJava { 
   public static void main(String[] args) { 
   
      //Connecting to Redis server on localhost 
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection to server sucessfully"); 
      
      //store data in redis list 
      jedis.lpush("tutorial-list", "Redis"); 
      jedis.lpush("tutorial-list", "Mongodb"); 
      jedis.lpush("tutorial-list", "Mysql"); 
      // Get the stored data and print it 
      List<String> list = jedis.lrange("tutorial-list", 0 ,5); 
      
      for(int i = 0; i<list.size(); i++) { 
         System.out.println("Stored string in redis:: "+list.get(i)); 
      } 
   } 
} 
Now, let's compile and run the above program.
$javac RedisListJava.java 
$java RedisListJava 
Connection to server sucessfully 
Stored string in redis:: Redis 
Stored string in redis:: Mongodb 
Stored string in redis:: Mysql

import redis.clients.jedis.Jedis; 

public class RedisKeyJava { 
   public static void main(String[] args) { 
   
      //Connecting to Redis server on localhost 
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection to server sucessfully"); 
      //store data in redis list 
      // Get the stored data and print it 
      List<String> list = jedis.keys("*"); 
      
      for(int i = 0; i<list.size(); i++) { 
         System.out.println("List of stored keys:: "+list.get(i)); 
      } 
   } 
}
Now, let's compile and run the above program.
$javac RedisKeyJava.java 
$java RedisKeyJava 
Connection to server sucessfully 
List of stored keys:: tutorial-name 
List of stored keys:: tutorial-list 

Before you start using Redis in your PHP programs, you need to make sure that you have Redis PHP driver and PHP set up on the machine. You can check PHP tutorial for PHP installation on your machine.
Now, let us check how to set up Redis PHP driver.
You need to download the phpredis from github repository https://github.com/nicolasff/phpredis. Once you’ve downloaded it, extract the files to phpredis directory. On Ubuntu, install the following extension.
cd phpredis 
sudo phpize 
sudo ./configure 
sudo make 
sudo make install 

Now, copy and paste the content of “modules” folder to the PHP extension directory and add the following lines in php.ini.
extension = redis.so

Now, your Redis PHP installation is complete
<?php 
   //Connecting to Redis server on localhost 
   $redis = new Redis(); 
   $redis->connect('127.0.0.1', 6379); 
   echo "Connection to server sucessfully"; 
   //check whether server is running or not 
   echo "Server is running: ".$redis->ping(); 
?>
When the program is executed, it will produce the following result.
Connection to server sucessfully 
Server is running: PONG 

<?php 
   //Connecting to Redis server on localhost 
   $redis = new Redis(); 
   $redis->connect('127.0.0.1', 6379); 
   echo "Connection to server sucessfully"; 
   //set the data in redis string 
   $redis->set("tutorial-name", "Redis tutorial"); 
   // Get the stored data and print it 
   echo "Stored string in redis:: " .$redis→get("tutorial-name"); 
?>
When the above program is executed, it will produce the following result.
Connection to server sucessfully 
Stored string in redis:: Redis tutorial 

<?php 
   //Connecting to Redis server on localhost 
   $redis = new Redis(); 
   $redis->connect('127.0.0.1', 6379); 
   echo "Connection to server sucessfully"; 
   //store data in redis list 
   $redis->lpush("tutorial-list", "Redis"); 
   $redis->lpush("tutorial-list", "Mongodb"); 
   $redis->lpush("tutorial-list", "Mysql");  
   
   // Get the stored data and print it 
   $arList = $redis->lrange("tutorial-list", 0 ,5); 
   echo "Stored string in redis:: "; 
   print_r($arList); 
?>
When the above program is executed, it will produce the following result.
Connection to server sucessfully 
Stored string in redis:: 
Redis 
Mongodb 
Mysql 

<?php 
   //Connecting to Redis server on localhost 
   $redis = new Redis(); 
   $redis->connect('127.0.0.1', 6379); 
   echo "Connection to server sucessfully"; 
   // Get the stored keys and print it 
   $arList = $redis->keys("*"); 
   echo "Stored keys in redis:: " 
   print_r($arList); 
?>
When the program is executed, it will produce the following result.
Connection to server sucessfully 
Stored string in redis:: 
tutorial-name 
tutorial-list 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page