Redis Tutorial: Introduction for Beginners
Redis, which stands for Remote Dictionary Server, is a powerful, open-source, in-memory data structure store. It’s used as a database, cache, message broker, and streaming engine. Unlike traditional databases that store data on disk, Redis keeps most of its data in RAM, making it exceptionally fast. This tutorial is designed for beginners with little to no prior experience with Redis, providing a comprehensive introduction to its core concepts and functionality.
Why Use Redis?
Redis offers several key advantages that make it popular for a wide range of applications:
- Speed: In-memory storage enables lightning-fast read and write operations. Typical operations take less than a millisecond.
- Data Structures: Redis supports a variety of rich data structures, including strings, lists, sets, sorted sets, hashes, bitmaps, hyperloglogs, and geospatial indexes. This allows for efficient storage and manipulation of diverse data types.
- Persistence (Optional): While primarily in-memory, Redis can persist data to disk using snapshots (RDB) or append-only files (AOF), ensuring data durability.
- Replication: Redis supports master-replica replication for high availability and read scaling.
- Transactions: Redis allows you to group commands into atomic transactions, ensuring that all commands either succeed or fail together.
- Pub/Sub: Redis offers a publish/subscribe messaging paradigm, making it suitable for building real-time applications.
- Lua Scripting: You can execute Lua scripts server-side, enabling complex operations and custom logic.
- Simplicity: Redis has a relatively simple command set and is easy to learn and use.
- Streaming Engine: Redis 5.0 and later includes Streams, a powerful data structure for building real-time data pipelines.
Key Concepts
Before diving into commands, let’s understand some core Redis concepts:
- Keys: Every piece of data in Redis is associated with a key. Keys are binary-safe strings, meaning they can contain any sequence of bytes. Key naming is crucial for organization. A common convention is to use colons (:) to create namespaces (e.g.,
user:123:name
). - Values: Values are the actual data stored under a key. Redis supports various data structures for values, allowing you to store different types of information.
- Data Structures: This is the core of Redis’s power. Understanding the different data structures is crucial for choosing the right one for your use case.
- Clients: To interact with a Redis server, you use a client. Clients exist for virtually every programming language.
redis-cli
is the command-line interface provided with Redis. - Commands: You interact with Redis by sending commands to the server. Commands are case-insensitive, but arguments are generally case-sensitive.
Installation
Installation varies depending on your operating system. Here’s a brief overview:
-
Linux (Ubuntu/Debian):
bash
sudo apt update
sudo apt install redis-server -
Linux (CentOS/RHEL):
bash
sudo yum install epel-release
sudo yum install redis
sudo systemctl enable redis
sudo systemctl start redis -
macOS (using Homebrew):
bash
brew install redis
brew services start redis # To start Redis automatically on boot -
Windows: Officially, Redis is not supported on Windows. However, you can use the Windows Subsystem for Linux (WSL) and install Redis on a Linux distribution within WSL, or use a third-party port like Memurai.
Connecting to Redis (redis-cli)
After installation, you can connect to the Redis server using the command-line client:
bash
redis-cli
This will connect to the default Redis server running on localhost
(127.0.0.1) and port 6379
. If your server is running on a different host or port, use:
bash
redis-cli -h <hostname> -p <port>
Once connected, you’ll see a prompt like this:
127.0.0.1:6379>
Basic Redis Commands and Data Structures
Now, let’s explore some fundamental Redis commands and their corresponding data structures:
-
Strings: The simplest data structure, storing a single string value.
SET key value
: Sets the value of a key.GET key
: Retrieves the value of a key.INCR key
: Increments the integer value of a key by one.DECR key
: Decrements the integer value of a key by one.APPEND key value
: Appends a value to the end of an existing string.STRLEN key
: Returns the length of the string stored at key.
127.0.0.1:6379> SET mykey "Hello"
OK
127.0.0.1:6379> GET mykey
"Hello"
127.0.0.1:6379> INCR counter
(integer) 1
127.0.0.1:6379> INCR counter
(integer) 2
127.0.0.1:6379> APPEND mykey " World"
(integer) 11
127.0.0.1:6379> GET mykey
"Hello World"
127.0.0.1:6379> STRLEN mykey
(integer) 11 -
Lists: Ordered collections of strings. Think of them as linked lists.
LPUSH key value1 [value2 ...]
: Prepends one or more values to a list.RPUSH key value1 [value2 ...]
: Appends one or more values to a list.LPOP key
: Removes and returns the first element of a list.RPOP key
: Removes and returns the last element of a list.LRANGE key start stop
: Returns a range of elements from a list (0-based indexing, -1 for the last element).LLEN key
: Returns the length of a list.
127.0.0.1:6379> LPUSH mylist "world"
(integer) 1
127.0.0.1:6379> LPUSH mylist "hello"
(integer) 2
127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "world"
127.0.0.1:6379> LPOP mylist
"hello"
127.0.0.1:6379> LRANGE mylist 0 -1
1) "world"
127.0.0.1:6379> LLEN mylist
(integer) 1 -
Sets: Unordered collections of unique strings.
SADD key member1 [member2 ...]
: Adds one or more members to a set.SREM key member1 [member2 ...]
: Removes one or more members from a set.SMEMBERS key
: Returns all members of a set.SISMEMBER key member
: Checks if a member exists in a set.SCARD key
: Returns the number of members in a set (cardinality).
127.0.0.1:6379> SADD myset "apple"
(integer) 1
127.0.0.1:6379> SADD myset "banana"
(integer) 1
127.0.0.1:6379> SADD myset "apple" # Adding a duplicate has no effect
(integer) 0
127.0.0.1:6379> SMEMBERS myset
1) "banana"
2) "apple"
127.0.0.1:6379> SISMEMBER myset "orange"
(integer) 0
127.0.0.1:6379> SISMEMBER myset "apple"
(integer) 1
127.0.0.1:6379> SCARD myset
(integer) 2 -
Hashes: Maps between string fields and string values. Similar to dictionaries or hash tables in other languages.
HSET key field value
: Sets the value of a field in a hash.HGET key field
: Gets the value of a field in a hash.HGETALL key
: Gets all fields and values of a hash.HDEL key field1 [field2 ...]
: Deletes one or more fields from a hash.HEXISTS key field
: Checks if a field exists in the hash.HLEN key
: Returns number of fields in the hash
127.0.0.1:6379> HSET user:123 name "Alice"
(integer) 1
127.0.0.1:6379> HSET user:123 age 30
(integer) 1
127.0.0.1:6379> HGET user:123 name
"Alice"
127.0.0.1:6379> HGETALL user:123
1) "name"
2) "Alice"
3) "age"
4) "30"
127.0.0.1:6379> HLEN user:123
(integer) 2 -
Sorted Sets: Similar to sets, but each member is associated with a score, used for ordering.
ZADD key score1 member1 [score2 member2 ...]
: Adds members with scores to a sorted set.ZRANGE key start stop [WITHSCORES]
: Returns a range of members, optionally with their scores.ZREM key member1 [member2 ...]
: Removes members from a sorted set.ZRANK key member
: Returns the rank of a member in the sorted set.ZCARD key
: Returns the number of members in a set (cardinality).ZSCORE key member
: Returns the score associated with a member.
“`
127.0.0.1:6379> ZADD leaderboard 100 “Alice”
(integer) 1
127.0.0.1:6379> ZADD leaderboard 150 “Bob”
(integer) 1
127.0.0.1:6379> ZADD leaderboard 80 “Charlie”
(integer) 1
127.0.0.1:6379> ZRANGE leaderboard 0 -1 WITHSCORES
1) “Charlie”
2) “80”
3) “Alice”
4) “100”
5) “Bob”
6) “150”
127.0.0.1:6379> ZCARD leaderboard
(integer) 3
127.0.0.1:6379> ZSCORE leaderboard “Alice”
“100”
“`
-
Key Expiration
EXPIRE key seconds
: Sets a timeout (in seconds) for a key. After the timeout, the key is automatically deleted.TTL key
: Returns the remaining time to live (TTL) of a key, in seconds. Returns -1 if the key does not have expire time, -2 if the key does not exist.PERSIST key
: Removes the timeout from a key, making it persistent.
“`
127.0.0.1:6379> SET mykey “temporary”
OK
127.0.0.1:6379> EXPIRE mykey 10
(integer) 1
127.0.0.1:6379> TTL mykey
(integer) 7
127.0.0.1:6379> GET mykey # After 10 seconds…
(nil)
127.0.0.1:6379> SET anotherkey “permanent”
OK
127.0.0.1:6379> EXPIRE anotherkey 10
(integer) 1
127.0.0.1:6379> PERSIST anotherkey
(integer) 1
127.0.0.1:6379> TTL anotherkey
(integer) -1``
DEL key1 [key2 …]` Deletes the specified keys
7. **Deleting keys**
*
127.0.0.1:6379> SET key1 "Hello"
OK
127.0.0.1:6379> SET key2 "World"
OK
127.0.0.1:6379> DEL key1 key2
(integer) 2
Beyond the Basics
This tutorial covers the fundamentals. Redis offers much more:
- Transactions (MULTI, EXEC, DISCARD, WATCH): For executing multiple commands atomically.
- Pub/Sub (PUBLISH, SUBSCRIBE, UNSUBSCRIBE): For building real-time messaging systems.
- Lua Scripting (EVAL, EVALSHA): For running custom logic on the server.
- Streams: For building real-time data pipelines.
- Modules: Redis can be extended using modules.
Next Steps
- Practice: The best way to learn is by doing. Experiment with the commands and data structures.
- Official Documentation: The official Redis documentation (https://redis.io/docs/) is an excellent resource.
- Redis Clients: Explore Redis clients for your preferred programming language.
- Use Cases: Think about how you can apply Redis to solve real-world problems, such as caching, session management, leaderboards, real-time analytics, and more.
- Redis University: Redis offers free online courses through Redis University (https://university.redis.com/).
This tutorial provides a solid foundation for your Redis journey. With its speed, versatility, and ease of use, Redis is a valuable tool for any developer’s arsenal.