Redis Tutorial
Redis Tutorial
Redis tutorial provides basic and advanced concepts of Redis Database. Our Redis tutorial is
designed for beginners and professionals both.
Our Redis Tutorial includes all topics of Redis such as what is redis, how to install redis,
redis commands, data types, keys, lists, strings, hashes, sets, sorted sets, transaction,
scripting, connection, server, interview questions etc.
What is Redis
Redis is a NoSQL database which follows the principle of key-value store. The key-value
store provides ability to store some data called a value, inside a key. You can recieve this
data later only if you know the exact key used to store it.
Redis is a flexible, open-source (BSD licensed), in-memory data structure store, used as
database, cache, and message broker. Redis is a NoSQL database so it facilitates users to
store huge amount of data without the limit of a Relational database.
Redis supports various types of data structures like strings, hashes, lists, sets, sorted sets,
bitmaps, hyperloglogs and geospatial indexes with radius queries.
Redis Architecture
There are two main processes in Redis architecture:
o Redis Client
o Redis Server
These client and server can be on same computer or two different computers.
Redis server is used to store data in memory . It controls all type of management and forms
the main part of the architecture. You can create a Redis client or Redis console client when
you install Redis application or you can use
Redis Index
Redis Tutorial
o Redis Tutorial
o Features of Redis
o Redis vs RDBMS
o Redis vs Other Key-value
o Installation on Windows
o Installation on Ubuntu
o Redis Configuration
o Redis Data types
o Redis All Commands
Redis Commands
o Redis Commands
o Redis Keys
o Redis Strings
o Redis Hashes
o Redis Lists
o Redis Sets
o Redis Sorted Sets
o Redis Transaction
o Redis Scripting
o Redis Connection
o Redis Server
Redis Advance
Redis Differences
o Redis vs Memcached
o Redis vs MongoDB
o Redis vs Elasticsearch
o Redis vs Aerospike
Interview Questions
Prerequisite
Before learning Redis, you must have the basic knowledge of SQL.
Audience
Our Redis Tutorial is designed to help beginners and professionals.
Problem
We assure that you will not find any problem in this Redis tutorial. But if there is any
mistake, please post the problem in contact form.
Speed: Redis stores the whole dataset in primary memory that's why it is extremely fast. It
loads up to 110,000 SETs/second and 81,000 GETs/second can be retrieved in an entry
level Linux box. Redis supports Pipelining of commands and facilitates you to use multiple
values in a single command to speed up communication with the client libraries.
Persistence: While all the data lives in memory, changes are asynchronously saved on disk
using flexible policies based on elapsed time and/or number of updates since last save.
Redis supports an append-only file persistence mode. Check more on Persistence, or read
the AppendOnlyFileHowto for more information.
Data Structures: Redis supports various types of data structures such as strings, hashes,
sets, lists, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes
with radius queries.
Atomic Operations: Redis operations working on the different Data Types are atomic, so it
is safe to set or increase a key, add and remove elements from a set, increase a counter
etc.
Sharding: Redis supports sharding. It is very easy to distribute the dataset across multiple
Redis instances, like other key-value store.
Portable: Redis is written in ANSI C and works in most POSIX systems like Linux, BSD, Mac
OS X, Solaris, and so on. Redis is reported to compile and work under WIN32 if compiled
with Cygwin, but there is no official support for Windows currently.
Redis RDBMS
In Redis, Read and Write operations are extremely fast In RDBMS, Read and Write operations
because of storing data in primary memory. of storing data in secondary memory.
Primary memory is in lesser in size and much expensive Secondary memory is in abundant in
than secondary so, Redis cannot store large files or binary primary memory so, RDBMS can easil
data. type of files.
Redis is used only to store those small textual information RDBMS can hold large data which has
which needs to be accessed, modified and inserted at a usage and not required to be very fas
very fast rate.
If you try to write bulk data more than the available
memory then you will receive errors.
o Redis is a different evolution path in the key-value databases where values can
contain more complex data types, with atomic operations defined on those data
types.
o Redis data types are closely related to fundamental data structures and are exposed
to the programmer as such, without additional abstraction layers.
o Redis is an in-memory but persistent on disk database, so 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 memory.
o 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, so Redis can do a lot, with little internal complexity.
o At the same time the two on-disk storage formats (RDB and AOF) don't need to be
suitable for random access, so they are compact and always generated in an
append-only fashion.
Scroll down to Windows section. You will see learn more. Click on it.
You will get release page:
Click on download:
You can see that Redis is downloaded now.
You can also download one click Redis and install as a Windows service by using the
following Github link.
https://github.com/rgl/redis/downloads
Start Redis
Redis is now ready to use. Start Redis server. Go to program files, followed by redis,
followed by:
Click on the redis-server.exe and you will find that the server is started.
You can see the Redis server. It will also specify that 1 client is connected.
First setup a non-root user using sudo and then install build and test dependencies:
1. sudo apt update
2. sudo apt full-upgrade
3. sudo apt install build-essential tcl
To continue press Y
Install Redis Server
Use the following command to install Redis server:
1. sudo apt-get install redis-server
Now Redis Server is installed. You can start the Redis server:
Start Redis Server
You the following command to start redis server:
1. redis-server
1. redis-cli
Verify if Redis is working
Execute the following command:
1. redis-cli
redis 127.0.0.1:6379>
In the above prompt, 127.0.0.1 is machine's IP address and 6379 is the port on which Redis
server is running.
Syntax
1. redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
Example
1. redis 127.0.0.1:6379> CONFIG GET loglevel
Output
1. "loglevel"
2. "notice"
Example
1. redis 127.0.0.1:6379> CONFIG GET *
Output
1. "dir"
2. "C:\\Program Files\\Redis"
3. "dbfilename"
4. "dump.rdb"
5. "requirepass"
6. (nil)
7. "masterauth"
8. (nil)
9. "maxmemory"
10. "0"
11. "maxmemory-policy"
12. "volatile-lru"
13. "maxmemory-samples"
14. "3"
15. "timeout"
16. "0"
17. "appendonly"
18. "no"
19. "no-appendfsync-on-rewrite"
20. "no"
21. "appendfsync"
22. "everysec"
23. "save"
24. "3600 1 300 100 60 10000"
25. "auto-aof-rewrite-percentage"
26. "100"
27. "auto-aof-rewrite-min-size"
28. "1048576"
29. "slave-serve-stale-data"
30. "yes"
31. "hash-max-zipmap-entries"
32. "512"
33. "hash-max-zipmap-value"
34. "64"
35. "list-max-ziplist-entries"
36. "512"
37. "list-max-ziplist-value"
38. "64"
39. "set-max-intset-entries"
40. "512"
41. "zset-max-ziplist-entries"
42. "128"
43. "zset-max-ziplist-value"
44. "64"
45. "slowlog-log-slower-than"
46. "10000"
47. "slowlog-max-len"
48. "64"
49. "loglevel"
50. "verbose"
Edit Configuration
To update configuration, you can edit redis.conf file directly or you can update
configurations via CONFIG set command.
Syntax
1. redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
Example
1. CONFIG GET "loglevel"
o Strings
o Hashes
o Lists
o Sets
o Sorted Sets
Strings
String is a set of bytes. In Redis database, strings are binary safe. It means they have a
known length and not determined by any special terminating characters. So it is possible to
store anything up to 512 megabytes in one string.
Example
Let's store a string name "Ajeet Kumar" in the key by using SET command and then retrieve
the same by using GET command.
1. SET name "Ajeet Kumar"
2. OK
3. GET name
4. "Ajeet Kumar"
In the above example, SET and GET are the Redis command, name is the key used in Redis,
"Ajeet Kumar" is string value stored in Redis.
Hashes
Hash is a collection of key-value pairs. In Redis, hashes are maps between string fields and
string values. So, they are used to represent objects.
Example
Let's store a user's object which contains basic information of a user.
1. HMSET user:1 username ajeet password javatpoint alexa 2000
2. OK
3. HGETALL user:1
4. "username"
5. "ajeet"
6. "password"
7. "javatpoint"
8. "alexa"
9. "2000"
Here, HMSET and HGETALL are the command for Redis, while user:1 is the key.
Every hash can store up to 232 - 1 field-value pairs (more than 4 billion).
Lists
Redis Lists are defined as a lists of strings, sorted by insertion order. You can add elements
to a Redis List on the head or on the tail.
Example
1. lpush javatpoint java
2. (integer) 1
3. lpush javatpoint java
4. (integer) 1
5. lpush javatpoint java
6. (integer) 1
7. lpush javatpoint java
8. (integer) 1
9. lrange javatpoint 0 10
10. "cassandra"
11. "mongodb"
12. "sql"
13. "java"
The max length of a list is 232 - 1 elements (more than 4 billion of elements per list).
Sets
Sets are an unordered collection of strings in Redis database. In Redis, you can add,
remove, and test for the existence of members in O(1) time complexity.
Example
1. sadd tutoriallist redis
2. (integer) 1
3. redis 127.0.0.1:6379> sadd tutoriallist sql
4. (integer) 1
5. redis 127.0.0.1:6379> sadd tutoriallist postgresql
6. (integer) 1
7. redis 127.0.0.1:6379> sadd tutoriallist postgresql
8. (integer) 0
9. redis 127.0.0.1:6379> sadd tutoriallist postgresql
10. (integer) 0
11. redis 127.0.0.1:6379> smembers tutoriallist
12. 1) "redis"
13. 2) "postgresql"
14. 3) "sql"
In the above example, you can see that postgresql is added thrice but due to unique
property of the set it is added only once.
The max number of members in a set is 232 - 1 elements (more than 4 billion of elements
per list).
Sorted Sets
Redis Sorted Sets are similar to Redis Sets. They are also a set of non-repeating collections
of Strings. But 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.
Example
1. redis 127.0.0.1:6379> zadd tutoriallist 0 redis
2. (integer) 1
3. redis 127.0.0.1:6379> zadd tutoriallist 0 sql
4. (integer) 1
5. redis 127.0.0.1:6379> zadd tutoriallist 0 postgresql
6. (integer) 1
7. redis 127.0.0.1:6379> zadd tutoriallist 0 postgresql
8. (integer) 0
9. redis 127.0.0.1:6379> zadd tutoriallist 0 postgresql
10. (integer) 0
11. redis 127.0.0.1:6379> ZRANGEBYSCORE tutoriallist 0 10
12. 1) "postgresql"
13. 2) "redis"
14. 3) "sql"
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type Perform arbitrary bitfield
offset increment] [OVERFLOW WRAP|SAT|FAIL] on strings
BITPOS key bit [start] [end] Find first bit set or clear
BLPOP key [key ...] timeout Remove and get the first
block until one is availab
BRPOP key [key ...] timeout Remove and get the last
block until one is availab
CLIENT KILL [ip:port] [ID client-id] [TYPE normal|master|slave|pubsub] Kill the connection of a cl
[ADDR ip:port] [SKIPME yes/no]
EVAL script numkeys key [key ...] arg [arg ...] Execute a Lua script serv
EVALSHA sha1 numkeys key [key ...] arg [arg ...] Execute a Lua script serv
GEOADD key longitude latitude member [longitude latitude member ...] Add one or more geospat
geospatial index represen
set
GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] Query a sorted set repres
[WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] index to fetch members m
[STOREDIST key] maximum distance from
GEORADIUSBYMEMBER key member radius m|km|ft|mi [WITHCOORD] Query a sorted set repres
[WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] index to fetch members m
[STOREDIST key] maximum distance from
HMGET key field [field ...] Get the values of all the
HMSET key field value [field value ...] Set multiple hash fields t
MIGRATE host port key|"" destination-db timeout [COPY] [REPLACE] Atomically transfer a key
[KEYS key [key ...]] instance to another one.
MSET key value [key value ...] Set multiple keys to mult
MSETNX key value [key value ...] Set multiple keys to mult
none of the keys exist
SET key value [EX seconds] [PX milliseconds] [NX|XX] Set the string value of a
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET Sort the elements in a lis
pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
ZADD key [NX|XX] [CH] [INCR] score member [score member ...] Add one or more membe
update its score if it alrea
Redis Commands
Redis commands are used for performing some operation on Redis Server. You must have a
Redis client to run Redis command.
Start Redis Client
To start Redis client, first go to "Program files" where Redis is installed. Open the folder
Redis and click on the "redis-server.exe".
After that, click on the Redis client. You will see this:
Now, you are connected with local server and you can run any command.
Let's write a command "PING". If it returns a response "PONG" that means you are
connected.
Syntax
1. $ redis-cli -h host -p port -a password
Example
Let's take an example to see how to connect to Redis remote server. Open command
prompt and run the following command:
1. redis-cli
Now the Redis port is open. You can use the "PING" command to check if it is connected.
Now you can see that the remote server is connected to Redis.
Redis Keys
Redis Keys are used with Redis command to manage themselves. See the syntax of using
Redis keys with commands.
Syntax:
1. redis 127.0.0.1:6379> COMMAND KEY_NAME
Example
Let's take an example of Redis key using with Redis DEL command. It will give an output 1,
if the key is deleted otherwise it will be 0.
1. redis 127.0.0.1:6379> SET javatpoint redis
2. OK
3. redis 127.0.0.1:6379> DEL javatpoint
4. (integer) 1
Here, "DEL" is a Redis command while "javatpoint" is a key.
2 DUMP key This command is used to return a serialized version of the value sto
key.
3 EXISTS key This command is used to check whether the key exists or not.
4 EXPIRE key This command is used to set the expiry of the key after the specifie
5 EXPIREAT key This command is used to set the expiry of the key after the specifie
in UNIX timestamp format.
6 PEXPIRE key This command is used to set the expiry of key in milliseconds.
7 PEXPIREAT key This command is used to set the expiry of the key in UNIX timestam
milliseconds.
8 KEYS pattern This command is used to find all keys matching the specified patter
15 RENAMENX key It is used to rename the key, if a new key doesn't exist.
newkey
16 TYPE key It is used to fetch the data type of the value stored in the key.
Redis String
Redis strings commands are used to manage string values in Redis. See the syntax for
using Redis string commands.
Syntax:
1. redis 127.0.0.1:6379> COMMAND KEY_NAME
Example
1. redis 127.0.0.1:6379> SET javatpoint redis
2. OK
3. redis 127.0.0.1:6379> GET javatpoint
4. "redis"
1 SET key value This command is used to set the value at the specified key
3 GETRANGE key start end This command is used to get a substring of the string store
4 GETSET key value This command is used to set the string value of a key and
5 GETBIT key offset This command is used to return the bit value at the offset
stored at the key.
6 MGET key1 [key2..] This command is used to get the values of all the given ke
7 SETBIT key offset value This command is used to set or clear the bit at the offset i
stored at the key
8 SETEX key seconds value This command is used to set the value with the expiry of a
9 SETNX key value This command is used to set the value of a key, only if the
10 SETRANGE key offset value This command is used to overwrite the part of a string at t
the specified offset
11 STRLEN key This command is used to retrieve the length of the value s
12 MSET key value [key This command is used to set multiple keys to multiple valu
value ...]
13 MSETNX key value [key This command is used to set multiple keys to multiple valu
value ...] the keys exist
14 PSETEX key milliseconds This command is used to set the value and expiration in m
value
16 INCRBY key increment This command is used to increment the integer value of a
amount
17 INCRBYFLOAT key increment This command is used to increment the float value of a ke
amount
19 DECRBY key decrement This command is used to decrement the integer value of a
number
Example
redis 127.0.0.1:6379> HMSET javatpoint name "A solution to all Technology" description
"India's fastest growing tutorial website" daily 1 million visitors 10 millions page visit.
1. OK
2. redis 127.0.0.1:6379> HGETALL javatpoint
3. 1) "name"
4. 2) "A solution to all Technology"
5. 3) "description"
6. 4) "India's fastest growing tutorial website"
7. 5) "daily"
8. 6) "1"
9. 7) "million"
10. 8) "visitors"
11. 9) "10"
12. 10) "millions"
13. 11) "page"
14. 12) "visit."
15. redis 127.0.0.1:6379>
In the above example, "javatpoint" is Redis hash which contains the details (name,
description, 1, million, 10, vistiors, page, visit) etc.
1 HDEL key field2 [field2] It is used to delete one or more hash fields.
3 HGET key field It is used to get the value of a hash field stored at
4 HGETALL key It is used to get all the fields and values stored in
specified key
5 HINCRBY key field increment It is used to increment the integer value of a hash
number
6 HINCRBYFLOAT key field increment It is used to increment the float value of a hash fie
amount
9 HMGET key field1 [field2] It is used to get the values of all the given hash fie
10 HMSET key field1 value1 [field2 It is used to set multiple hash fields to multiple va
value2 ]
11 HSET key field value It is used to set the string value of a hash field
12 HSETNX key field value It is used to set the value of a hash field, only if th
exist
Redis Lists
Redis lists can be defined as a list of strings, sorted by insertion order. You can add
elements in Redis lists in the head or the tail of the list.
Example
1. redis 127.0.0.1:6379> LPUSH javatpoint sql
2. (integer) 1
3. redis 127.0.0.1:6379> LPUSH javatpoint mysql
4. (integer) 2
5. redis 127.0.0.1:6379> LPUSH javatpoint cassandra
6. (integer) 3
7. redis 127.0.0.1:6379> LRANGE javatpoint 0 10
8. 1) "cassandra"
9. 2) "mysql"
10. 3) "sql"
11. redis 127.0.0.1:6379>
Redis Lists Commands
1 BLPOP key1 [key2 ] timeout It is used to remove and get the first element in a list, o
available.
2 BRPOP key1 [key2 ] timeout It is used to remove and get the last element in a list, or
available.
4 LINDEX key index It is used to get an element from a list by its index.
5 LINSERT key before|after pivot It is used to insert an element before or after another el
value
7 LPOP key It is used to remove and get the first element in a list.
8 LPUSH key value1 [value2] It is used to prepend one or multiple values to a list.
9 LPUSHX key value It is used to prepend a value to a list, only if the list exis
10 LRANGE key start stop It is used to get a range of elements from a list.
12 LSET key index value It is used to set the value of an element in a list by its in
13 LTRIM key start stop It is used to trim a list to the specified range.
14 RPOP key It is used to remove and get the last element in a list.
15 RPOPLPUSH source destination It is used to remove the last element in a list, append it
returns it.
16 RPUSH key value1 [value2] It is used to append one or multiple values to a list.
17 RPUSHX key value It is used to append a value to a list, only if the list exist
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 more than 4 billion of elements per set.
EXAMPLE
1. redis 127.0.0.1:6379> SADD javatpoint db2
2. (integer) 1
3. redis 127.0.0.1:6379> SADD javatpoint mongodb
4. (integer) 1
5. redis 127.0.0.1:6379> SADD javatpoint db2
6. (integer) 0
7. redis 127.0.0.1:6379> SADD javatpoint cassandra
8. (integer) 1
9. redis 127.0.0.1:6379> SMEMBERS javatpoint
10. 1) "cassandra"
11. 2) "db2"
12. 3) "mongodb"
In the above example, you can see that we have added 4 elements in the set by using
SADD command. But only 3 elements are retrieved by using SMEMBERS command because
one element was duplticate and Redis sets read duplicate values only once.
4 SDIFFstore destination key1 [key2] It is used to subtract multiple sets and store
in a key.
6 SINTERSTORE destination key1 [key2] It is used to intersect multiple sets and stor
in a key.
13 SUNIONSTORE destination key1 [key2] It is used to add multiple sets and stores th
key.
14 SSCAN key cursor [match pattern] [count It is used to incrementally iterates set elem
count]
Example
1. redis 127.0.0.1:6379> ZADD javatpoint 1 redis
2. (integer) 0
3. redis 127.0.0.1:6379> ZADD javatpoint 2 cassandra
4. (integer) 1
5. redis 127.0.0.1:6379> ZADD javatpoint 3 cassandra
6. (integer) 0
7. redis 127.0.0.1:6379> ZADD javatpoint 3 mysql
8. (integer) 1
9. redis 127.0.0.1:6379> ZADD javatpoint 4 mysql
10. (integer) 0
11. redis 127.0.0.1:6379> ZRANGE javatpoint 0 10 WITHSCORES
12. 1) "redis"
13. 2) "1"
14. 3) "cassandra"
15. 4) "3"
16. 5) "mysql"
17. 6) "4"
1 ZADD key score1 member1 [score2 It is used to add one or more members to a so
member2] updates its score, if it already exists
8 ZRANGEBYLEX key min max [LIMIT offset It is used to return a range of members in a s
count] lexicographical range
11 ZREM key member [member ...] It is used to remove one or more members fro
19 ZUNIONSTORE destination numkeys key It is used to add multiple sorted sets and stor
[key ...] sorted set in a new key
20 ZSCAN key cursor [MATCH pattern] It is used to incrementally iterates sorted sets
[COUNT count] associated scores
Sample
In Redis, transaction is initiated by using "MULTI" command 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.
Example
Let's take an example to see how Redis transaction can be initiated and executed.
Example
1. redis 127.0.0.1:6379> MULTI
2. OK
3. redis 127.0.0.1:6379> EXEC
4. (empty list or set)
5. redis 127.0.0.1:6379> MULTI
6. OK
7. redis 127.0.0.1:6379> SET javatpoint redis
8. QUEUED
9. redis 127.0.0.1:6379> GET javatpoint
10. QUEUED
11. redis 127.0.0.1:6379> INCR visitors
12. QUEUED
13. redis 127.0.0.1:6379> EXEC
14. 1) OK
15. 2) "redis"
16. 3) (integer) 1
5 WATCH key It is used to watche the given keys to determine the execution of th
[key ...] block
Syntax
1. redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]
Example
1. redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1
2. key2 first second
3. 1) "key1"
4. 2) "key2"
5. 3) "first"
6. 4) "second"
Example
Following example explains how a client authenticates itself to Redis server and checks
whether the server is running or not.
1. redis 127.0.0.1:6379> AUTH "password"
2. (error) ERR Client sent AUTH, but no password is set
3. redis 127.0.0.1:6379>
4. redis 127.0.0.1:6379> PING
5. PONG
6. redis 127.0.0.1:6379>
Note: Here you can see that "password" is not set so you can access any command directly.
1 AUTH password It is used to authenticate to the server with the given password.
2 ECHO message It is used to print the given string.
5 SELECT index It is used to change the selected database for the current connectio
Example
Let's take an example to see how to get all statistics and information about the server.
1. redis 127.0.0.1:6379> ping
2. PONG
3. redis 127.0.0.1:6379> AUTH "password"
4. (error) ERR Client sent AUTH, but no password is set
5. redis 127.0.0.1:6379> PING
6. PONG
7. redis 127.0.0.1:6379> ECHO "Welcome to Javatpoint"
8. "Welcome to Javatpoint"
9. redis 127.0.0.1:6379> INFO
10. redis_version:2.4.6
11. redis_git_sha1:26cdd13a
12. redis_git_dirty:0
13. arch_bits:64
14. multiplexing_api:winsock2
15. gcc_version:4.6.1
16. process_id:6360
17. uptime_in_seconds:4442
18. uptime_in_days:0
19. lru_clock:1716856
20. used_cpu_sys:1.80
21. used_cpu_user:0.42
22. used_cpu_sys_children:0.00
23. used_cpu_user_children:0.00
24. connected_clients:1
25. connected_slaves:0
26. client_longest_output_list:0
27. client_biggest_input_buf:0
28. blocked_clients:0
29. used_memory:1188152
30. used_memory_human:1.13M
31. used_memory_rss:1188152
32. used_memory_peak:1188112
33. used_memory_peak_human:1.13M
34. mem_fragmentation_ratio:1.00
35. mem_allocator:libc
36. loading:0
37. aof_enabled:0
38. changes_since_last_save:0
39. bgsave_in_progress:0
40. last_save_time:1506142039
41. bgrewriteaof_in_progress:0
42. total_connections_received:1
43. total_commands_processed:4
44. expired_keys:0
45. evicted_keys:0
46. keyspace_hits:0
47. keyspace_misses:0
48. pubsub_channels:0
49. pubsub_patterns:0
50. latest_fork_usec:0
51. vm_enabled:0
52. role:master
Redis Server Commands
Following is a list of some server commands used in Redis database:
Inde Command Description
x
3 CLIENT KILL [ip:port] [ID client-id] This command is used to kill the connection of a
4 CLIENT LIST This command is used to get the list of client con
server.
7 CLIENT SETNAME connection-name This command is used to set the current connec
14 CONFIG GET parameter This command is used to get the value of a conf
16 CONFIG SET parameter value This command is used to get a configuration par
value.
29 SLAVEOF host port This command is used to make the server a slav
instance, or promotes it as a master .
30 SLOWLOG subcommand [argument] This command is used to manage the Redis slow
Syntax
1. SAVE
Return Value
SAVE
"/var/lib/redis"
BGSAVE Command
There is an alternate command named BGSAVE which is used to create Redis backup.
This command will start the backup process and run this in the background.
Syntax
1. BGSAVE
Example
You need to set a password in the config file to secure a Redis databse.
Example
Let's see how to secure your Redis instance.
1. config get requirepass
You can see that the above property is blank means we don't have any password for this
instance. You can change this property and set a password for this instance by executing
the following command.
1. config set requirepass "javatpoint123"
1. CONFIG get requirepass
When you set this password then if a client runs the command without authentication, he
will get an error "NOAUTH Authentication required.". Hence, the client needs to use AUTH
command to authenticate himself.
Usage of AUTH Command
1. 127.0.0.1:6379> AUTH "javatpoint123"
2. OK
3. 127.0.0.1:6379> SET mykey "hindi100"
4. OK
5. 127.0.0.1:6379> GET mykey
6. "hindi100"
7. 127.0.0.1:6379>
Syntax
1. redis-benchmark [option] [option value]
Example
Let's call Redis Benchmarkcommands:
redis-benchmark -n 100000
See the list of available options in Redis benchmark:
Example
Let's take an example to show multiple usage options in Redis benchmark utility.
1. redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 100000 -q
o The client socket is put in non-blocking state since Redis uses multiplexing and non-
blocking I/O.
o The TCP_NODELAY option is set in order to ensure that we don't have delays in our
connection.
o 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.
1. Config get maxclients
2. "maxclients"
3. "4064"
The maximum number of clients depends upon the maximum number of file descriptors
limit of OS. Its default value is 10000, although you can change this property.
Example
Let's take an example to set the maximum number of clients to 100000, while starting the
server.
1. redis-server --maxclients 100000
Client Commands
3 CLIENT Returns the name of the current connection as set by CLIENT SETNAME
GETNAME
4 CLIENT PAUSE This is a connections control command able to suspend all the Redis clien
amount of time (in milliseconds)
o The client sends a query to the server usually in a blocking way for the server
response.
o The server processes the command and sends the response back to the client.
What is Pipelining
Pipelining facilitates a client to send multiple requests to the server without waiting for the
replies at all, and finally reads the replies in a single step.
Example
Let's see an example of Redis pipelining. In this example, we will submit multiple commands
to Redis once and Redis will provide the output of all commands in a single step.
1. (echo -en "PING\r\n SET sssit javatraining\r\n GET sssit\r\n INCR visitor\r\n INCR vi
sitor\r\n INCR visitor\r\n"; sleep 10) |
2. nc localhost 6379
Here:
Advantage of Pipelining
The main advantage of Redis pipelining is speeding up the Redis performance. It drastically
improves the protocol performance because of multiple commands simultaneous execution.
Pipelining vs Scripting
Redis Scripting is available in Redis version 2.6 or greater. A lot number of use cases for
pipelining can be addressed more efficiently using scripts that perform a lot of the work
needed at the server side.
The main advantage of scripting is that it can both read and write data with minimal
latency. It makes operations like read, compute, write very fast.
On the other hand, pipelining doesn't use this scenerio. In pipelining, the client needs the
reply of the read command before it can call the write command.
Types of Partitioning
There are two types of partitioning in redis:
o Range Partitioning
o Hash Partitioning
Range Partitioning
Range partitioning is one of the simpliest way to perform partitioning. It is done by mapping
ranges of objects into specific Redis instances.
For example:
Suppose that you have 3000 users. So you can say that users from ID 0 to ID 1000 will go
into instance R0, while users form ID 1001 to ID 2000 will go into instance R1, users form
ID 2001 to ID 3000 will go into instance R2 and so forth.
Hash Partitioning
Hash partitioning is an alternative of Range partitioning. In Hash partitioning, a hash
function is used to convert the key into a number and then the data is stored in different-
different Redis instances.
o Partitioning doesn't usually support the operations which have multiple keys. For
example, you can't perform the intersection between two sets if they are stored in
keys that are mapped to different Redis instances.
o Partitioning doesn't support the transactions which have multiple keys.
o The partitioning granularity is the key, so it is not possible to shard a dataset with a
single huge key like a very big sorted set.
o When partitioning is used, data handling is more complex, for instance you have to
handle multiple RDB / AOF files, and to make a backup of your data you need to
aggregate the persistence files from multiple instances and hosts.
o Adding and removing capacity can be complex. For instance Redis Cluster supports
mostly transparent rebalancing of data with the ability to add and remove nodes at
runtime, but other systems like client side partitioning and proxies don't support this
feature. However a technique called Pre-sharding helps in this regard.
Next Topic #
Redis Vs Memcached
Comparison Memcached Redis
Index
Description MemcacheD is easy, simply designed yet Redis is an open source in-
powerful. Its simple design promotes fast structure store which also
deployment, ease of exaggeration, and solves database as well as cachin
many problems related to large data caches. It almost all types of data str
has its inbuilt APIs which provide a very large strings, hashes, lists, sets,
hash table distributed across multiple machines range queries, bitmaps, hy
& uses internal memory management to geospatial indexes through
provide more efficiency. MemcacheD supports Redis also can be used for
only String data type which are ideal for used as pub/sub.
storing read-only data. Memcached is a volatile
in-memory key-value origin. It is multi-
threaded and used primarily for caching
objects.
Primary database Memcached follows Key-value store database Redis also follows Key-valu
model model. model.
Initial release Memcached was initially released in 2003. Redis was initially released
Current release Memcached current version is 1.5.1, released Redis current version is 4.0
in August 2017. September 2017.
License Memcached is free and open source. Redis is also free and open
Cloud-based No No
Supported .Net, C, C++, ColdFusion, Erlang, Java, Lisp, C,C#,C++, Clojure, Crysta
programming Lua, OCaml, Perl, PHP, Python, Ruby Erlang, Fancy, Go, Haskell,
languages JavaScript (Node.js), Lisp,
Objective-C, OCaml info, P
Pure Data, Python, R, Rebo
Scala, Scheme, Smalltalk,
Server-side No Lua
scripts
Triggers No No
MapReduce No No
Foreign keys No No
Durability No Yes
Memory Usage MemcacheD is more memory efficient than Redis is more memory effic
Redis because it consumes comparatively less use Redis hashes.
memory resources for metadata.
Persistence Memcached doesn't use persistent data. While Redis can handle persisten
using Memcached, data might be lost with a syncs data to the disk at le
restart and rebuilding cache is a costly process. seconds, offering optional
persistence meant to boots
a planned shutdown or an
failure. While we tend to re
caches as volatile and tran
data to disk can be quite v
scenarios.
Storage type MemcacheD stores variables in its memory and Redis is like a database tha
retrieves any information directly from the memory. It executes (read
server memory instead of hitting the database key/value pair from its dat
again. result set. That's why it is
for real-time metrics and a
Execution Speed MemcacheD is very good to handle high traffic Redis can neither handle h
and Performance websites. It can read many information at a nor heavy writes.
time and give you back at a great response
time.
Data Structure MemcacheD uses only strings and integers in Redis has stronger data str
its data structure. So, everything you save can handle not only strings inte
either be a string or an integer. It is binary-safe strings, lists of
complicated because with integers, the only sets of binary-safe strings
data manipulation you can do is adding or
subtracting them. If you need to save arrays or
objects, you will have to serialize them first
and then save them. To read them back, you
will need to un-serialize.
Key Length Memcached's key length has a maximum of Redis' key-length has a ma
250 bytes.
Introduction Redis is in-memory data structure store, MongoDB is one of the most p
used as database, cache and message database which follows the do
broker. structure.
Technical You can get technical documentation of Redis You can get technical docume
Documentation on redis.io/documentation on docs.mongodb.com/manu
Initial Release Redis is initially released in 2009. MongoDB is also initially relea
Licence Redis is subscription based and open-source. MongoDB is free to use and o
Cloud based No No
Secondary No Yes
Indexes
SQL No No
APIs and other Redis follows proprietary protocol. MongoDB follows proprietary
access methods JSON.
Supported C, C#, C++, Clojure, Crystal, D, Dart, Elixir, Actionscript, C, C#, C++, Clo
programming Erlang,Fancy, Go, Haskell, Haxe, Java, Dart, Delphi, Erlang, Go, Groo
languages JavaScript (Node.js), Lisp, Lua, MatLab, JavaScript, Lisp, Lua, MatLab
Objective-C, OCaml, Perl, PHP, Prolog, Pure PowerShell, Prolog, Python, R
Data, Python, R, Rebol, Ruby, Rust, Scala, Smalltalk
Scheme, Smalltalk, Tcl
Triggers No No
Partitioning Redis uses Sharding for partition. MongoDB also uses Sharding
methods
MapReduce No Yes
Foreign keys No No
MapReduce No Yes
User concepts Simple password-based access control. Access rights for users and ro
Key Customers Key customers of Redis are: Verizon, Key customers of MongoDB a
Vodafone, Atlassian, Trip Advisor, Jet.com, AstraZeneca, BBVA, Bosch, C
Nokia, Samsung, HTC, Docker, Staples, Department of Veteran Affairs
Intuit, Groupon, Shutterfly, KPMG, TD Bank, Electronic Arts, Expedia, Face
UnitedHealthcare, RingCentral, The Motley Forbes, Foursquare, Genentec
Fool, Bleacher Report, HipChat, Salesforce, Sage, Salesforce, The Weathe
Hotel Tonight, Cirruspath, Itslearning.com, Ticketmaster, Under Armour,
Xignite, Chargify, Rumble Entertainment, etc.
Scopely, Havas Digital, Revmob, MSN,
Bleacher Report, Mobli, TMZ, Klarna, Shopify
etc.
Market Metrics Redis Labs consists of more than 60000 20 million downloads (growin
customers globally and is consistently ranked downloads per day). More tha
as a leader in top analyst reports on NoSQL, including over one third of the
in-memory and operational databases. Redis Named a leader in the Forres
is rated as no. 1 cloud database, no.1 NoSQL, Q3 2016. Highest pla
database in Docker, no.1 NoSQL datastore, database in DB Engines ranki
most popular NoSQL database in container.
DB-Engines Score120.41 Overall Rank #9 Rank in Key- Score 120.00 Overall Rank
Ranking value stores #7 Search engines #1
Cloud-based info no no
Implementation C Java
language
XML support no
Secondary no yes
indexes
SQL no no
Supported C C# C++ Clojure Crystal D Dart Elixir Erlang .Net Clojure Erlang Go Gro
programming Fancy Go Haskell Haxe Java JavaScript JavaScript Lua Perl PHP Py
languages (Node.js) Lisp Lua MatLab Objective-C OCaml
Perl PHP Prolog Pure Data Python R Rebol Ruby
Rust Scala Scheme Smalltalk Tcl
Triggers no yes
MapReduce no no
Foreign keys no no
Cloud-based No No
XML support No No
Secondary No Yes
indexes
SQL No No
Supported C, C#, C++, Clojure, Crystal, D, Dart, Elixir, .Net, C, C#, C++, Erlang, G
programming Erlang, Fancy, Go, Haskell, Haxe, Java, (Node.js), Lua, Perl, PHP, Py
languages JavaScript (Node.js), Lisp, Lua, MatLab,
Objective-C, OCaml info, Perl, PHP, Prolog,
Pure Data, Python, R, Rebol, Ruby, Rust,
Scala, Scheme, Smalltalk, Tcl
Triggers No No
MapReduce No Yes
Foreign keys No No
User concepts Simple password-based access control Access rights for users and r
Special Redis is ranked as world?s fastest database. It Aerospike is an enterprise-cl
Characterstics reduces application complexity, simplifies database solution delivering
development, accelerates time to market and performance at scale, superi
provides unprecedented flexibility to availability at the lowest cos
developers with its visionary data structures generation NoSQL or relation
and modules. Aerospike was mainly built w
parallelized architecture to s
Big Data-driven applications
scale up and out.
Comparing Redis is an in-memory database platform Optimized for use with SSDs
Advantages provides support of wide range of data drives) Scales horizontally a
structures such as strings, hashes, sets, lists, sharding & auto-healing Sma
sorted sets, bitmaps, hyperloglogs, and mission-critical deployments
geospatial indexes. Redis provides effortless companies across many indu
scaling in a fully automated manner by
overseeing all the operations of sharding, re-
sharding, migration. It also includes
persistence, instant automatic failure
detection, backup and recovery, and in-
memory replication across racks, zones,
datacenters, regions, and cloud platforms.
Key Customers Key customers of Redis are: Verizon, Key customers of Aerospike
Vodafone, Atlassian, Trip Advisor, Jet.com, Williams-Sonoma, Inmobi, A
Nokia, Samsung, HTC, Docker, Staples, Intuit, (confidential), Financial Serv
Groupon, Shutterfly, KPMG, TD Bank, Partners include Intel, Sams
UnitedHealthcare, RingCentral, The Motley Services, Cloudera, Dell and
Fool, Bleacher Report, HipChat, Salesforce,
Hotel Tonight, Cirruspath, Itslearning.com,
Xignite, Chargify, Rumble Entertainment,
Scopely, Havas Digital, Revmob, MSN,
Bleacher Report, Mobli, TMZ, Klarna, Shopify
etc.
Market Metrics Redis Labs consists of more than 60000 Aerospike is a combination o
customers globally and is consistently ranked and reliability. It delivers 10
as a leader in top analyst reports on NoSQL, or 1/10th the cost compared
in-memory and operational databases. Redis
is rated as no. 1 cloud database, no.1
database in Docker, no.1 NoSQL datastore,
most popular NoSQL database in container.