Tutorial Playlist
Redis is an open-source, in-memory data structure store widely used for caching, real-time analytics, messaging, and more. In this tutorial, you’ll go through the fundamental concepts of Redis, its various data types, commands, and practical use cases.
Whether you're a beginner looking to get started or an experienced developer seeking advanced insights, this tutorial will help you with the knowledge to understand Redis's power for efficient data storage and manipulation.
Welcome to the Redis lesson, where you'll learn everything there is to know about this flexible and fast in-memory data structure store.
Remote Dictionary Server, or Redis, is well-known for its quickness, adaptability, and different data storage and manipulation capabilities. Redis is vital in the developer's toolbox because of its speed, simplicity, and wide range of uses. By the end of this lesson, you will have the skills and assurance necessary to successfully incorporate Redis into your applications, including caching, real-time analytics, and more.
It’s an open-source, high-performance data structure store for versatile tasks. Speed, simplicity, and broad applications, including caching, analytics, and messaging.
1. Caching: Redis caches frequently accessed data, reducing database queries.
2. Real-Time Analytics: Stores and processes real-time analytics data efficiently.
3. Session Management: Quick access to user sessions without database queries.
4. Leaderboards and Counting: Sorted sets for leaderboards and counting operations.
Let’s delve into Redis's architecture with examples.
1. Redis Client:
A Redis client is a program that connects to the Redis server, sending commands and fetching data. Clients can be coded in different languages and handle server connections.
Example of Using a Redis Client (Python):
import redis
# Connect to the Redis server
client = redis. Redis (host='localhost', port=6379, db=0)
# Set a key-value pair
client.set('name', 'John')
# Get the value for a key
value = client.get('name')
print(value.decode('utf-8')) # Output: John
2. Redis Server:
The Redis server stores data in memory, processes client commands, handles keys and values, supports data types, and performs data operations.
Example of Redis Server Operations:
# Set a key-value pair
> SET name "Alice"
OK
#Retrieve the value for a key
>GET name
"Alice"
#Increment a counter
> INCR counter
(integer) 1
#Store a list of values
>LPUSH mylist "apple" (integer) 1
>LPUSH mylist "banana" (integer) 2
#Retrieve values from the list
>LRANGE mylist @ -1
1 "banana"
2 "apple"
Key features with examples:
1. In-Memory Speed: Lightning-fast read and write operations.
Example: Store user sessions or product data for quick access.
2. Versatile Data Types: Strings, lists, sets, hashes, and more.
Example: Create leaderboards with sorted sets.
3. Atomicity: Commands are atomic for data consistency.
Example: Safe counter increments in multi-client settings.
4. Persistence Options: Snapshots and append-only files for data durability.
Example: Periodic snapshots to prevent data loss.
5. Pub/Sub Messaging: Real-time updates with publish/subscribe.
Example: Instant chat messages in a chat application.
6. Transactions: Execute multiple commands atomically.
Example: Update account balance and log in one step.
7. Key Expiration: Set keys to auto-expire for cache management.
Example: Short TTL for cache clearing.
Redis is an in-memory data store with disk persistence, ideal for caching and database tasks, supporting various data types for versatility.
Redis Data types
Redis supports various data types, each designed to serve specific use cases. Let's explore these data types with examples:
1. Strings:
Strings are the most basic data type and can store text or binary data, such as numbers or serialized objects.
Example:
2. Lists:
Lists are ordered collections of strings, allowing duplicates and maintaining the insertion order.
Example:
3. Sets:
Sets are unordered collections of unique strings, providing set operations like union, intersection, and difference.
Example:
4. Hashes:
Hashes store field-value pairs, useful for representing objects with multiple attributes.
Example:
5. Sorted Sets:
Sorted sets store unique strings along with a numeric score, allowing sorting and ranking of elements.
Example:
6. Bitmaps:
Bitmaps are a special data type that can store and manipulate bits. They're used for efficient storage and manipulation of binary data.
Example:
7. HyperLogLogs:
HyperLogLogs are used to estimate the cardinality of a set, such as counting unique items.
Example:
1. Data Model:
2. Performance:
3. Scalability:
4. Data Consistency:
Example: Redis caches article titles; RDBMS stores full content in a news website.
Comparison of Redis with other key-value stores using examples:
1. Redis:
2. Memcached:
3. Amazon DynamoDB:
4. Couchbase:
5. Riak:
Installing Redis on Windows involves a few steps to set up the Redis server. Here's a step-by-step guide with examples:
1. Download Redis:
Download the Redis for Windows binaries from the official GitHub repository: https://github.com/MicrosoftArchive/redis/releases
2. Extract Files:
Extract the downloaded ZIP file to a directory of your choice. For example, let's extract it to 'C:\redis'.
3. Configuration:
Inside the extracted directory, you'll find a 'redis.windows.conf' file. Rename this file to 'redis.conf'.
4. Running the Server:
Open a Command Prompt and navigate to the Redis directory (e.g., 'C:\redis' ).
Start the Redis server by running:
You should see the server starting and listening on the default port 6379.
5. Testing the Server:
Open another Command Prompt window and navigate to the Redis directory.
Use the Redis CLI to interact with the server:
You can now run Redis commands like 'SET', 'GET', and others to interact with the server:
6. Stopping the Server:
To stop the Redis server, return to the Command Prompt where the server is running and press 'Ctrl+C'.
Installing Redis on Ubuntu is straightforward using the package manager. Here's a step-by-step guide with examples:
1. Update Package Repository:
In a terminal, update the package repository to get the latest Redis version.
2. Install Redis:
Use the 'apt' package manager to install Redis.
3. Start and Enable Redis:
4. Testing Redis:
Now you're in the Redis CLI, and you can run commands like 'SET', 'GET', and more:
5. Stopping Redis:
If needed, you can stop the Redis service with the following command:
Ubuntu system is currently running Redis. Edit the "/etc/redis/redis.conf" file to suit your needs to change its configuration, including memory and security options.
1. Binding and Network Configuration:
The 'bind' directive controls the network interfaces Redis listens on, with all interfaces as the default setting.
Example:
2. Port Configuration:
The 'port' directive specifies the port on which Redis listens for incoming connections.
Example:
3. Memory Configuration:
Redis uses 'maxmemory' to set memory limits and eviction policies when memory is full.
Example:
4. Persistence Configuration:
Redis supports different persistence mechanisms. The 'save' directive defines the frequency of snapshots to be saved to disk.
Example:
5. Security Configuration:
You can set a password for authentication using the requirepass directive.
Example:
6. Logging Configuration:
The 'logfile' directive specifies the location of the log file.
Example:
7. Replication Configuration:
If you're using replication, you can set the 'slaveof' directive to specify the master server.
Example:
8. Clustering Configuration:
For Redis clustering, you can define the cluster's initial nodes using the 'cluster-announce-ip' and 'cluster-announce-port' directives.
Example:
9. Lua Scripting Configuration:
To enable or disable Lua scripting, use the 'lua-scripting' directive.
Example:
10. Limiting Client Connections:
The 'maxclients' directive limits the number of simultaneous client connections.
Example:
Redis offers various commands for data manipulation. Here's an overview of common Redis commands with examples:
1. String Commands:
- SET key value: Set a string value.
- GET key: Get the value of a key.
- INCR key: Increment the integer value of a key by 1.
2. List Commands:
- LPUSH key value: Push a value to the beginning of a list.
- LRANGE key start stop: Retrieve a range of elements from a list.
3. Set Commands:
- SADD key member: Add a member to a set.
- SMEMBERS key: Get all members of a set.
4. Hash Commands:
- HSET key field value: Set the value of a field in a hash.
- HGET key field: Get the value of a field in a hash.
5. Sorted Set Commands:
- ZADD key score member: Add a member with a score to a sorted set.
- ZRANK key member: Get the rank of a member in a sorted set.
6. Key Management Commands:
- DEL key: Delete a key and its associated data.
- EXPIRE key seconds: Set a key's time to live (TTL) in seconds.
7. Pub/Sub Commands:
- PUBLISH channel message: Publish a message to a channel.
- SUBSCRIBE channel: Subscribe to a channel.
8. Transaction Commands:
- MULTI: Start a transaction.
- EXEC: Execute a transaction.
9. Scripting Commands:
- EVAL script numkeys key [key ...] arg [arg ...]: Execute a Lua script.
10. Server Commands:
- INFO: Get information about the Redis server.
- PING: Check if the server is running.
These are just a few examples of Redis commands.
Let's explore the process with examples.
1. Backup:
To create a Redis backup, use 'SAVE' or 'BGSAVE' commands. 'SAVE' blocks Redis, while 'BGSAVE' creates a non-blocking backup. Consider production needs when choosing between them.
- Using BGSAVE:
2. Restore:
To restore data from a backup, follow these steps:
- Stop the Redis server.
- Delete the existing 'dump.rdb' file (if present) from the Redis data directory.
- Place the backup RDB file (usually named 'dump.rdb') in the Redis data directory.
- Start the Redis server.
Example Scenario:
Let's say you want to create a backup of your Redis data and restore it:
Backup:
Run the 'BGSAVE' command to create a backup.
EVAL "local balance = tonumber (redis.call('GET', 'account_balance"));
return balance > 1000 and redis.call('SET', 'high_balance', 'true") or
redis.error('Balance too low’) " 0
Here's a quick example of using Redis with Java:
import redis.clients.jedis. Jedis;
public class RedisExample {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
jedis.set("key", "value");
System.out.println(“Value for key: “ + jedis.get());
}
}
Redis Scripting enables custom operations on the Redis server using Lua. It's ideal for complex tasks beyond Redis's built-in commands.
1. Writing and Executing a Lua Script:
Example: Lua Script to Increment a Key by 1
local key = KEYS[1]
local currentValue = tonumber(redis.call('GET', key))
if currentValue then
redis.call('SET', key, currentValue + 1)
end
Execute the script using the EVAL command:
EVAL "local key = KEYS [1] local currentValue = tonumber(redis.call(‘GET’,
key)) if currentValue then redis.call('SET', key, currentValue + 1) end”
1 mycounter
2. Using KEYS and ARGV:
Example: Lua Script to Increment with Custom Value
local key = KEYS[1]
local incrementBy = tonumber (ARGV[1])
local currentValue = tonumber (redis.call('GET', key))
if currentValue then
redis.call( ET" key, currentValue + incrementBy)
end
Execute the script:
EVAL "local key KEYS [1] local incrementBy = tonumber (ARGV[1]) local = currentValue = tonumber (redis.call('GET', key)) if currentValue then redis.call('SET', key, currentValue + incrementBy) end" 1 mycounter 5
3. Lua Scripting for Atomic Operations:
Example: Using Lua Script to Perform Conditional Update
local key = KEYS[1]
local expectedValue = ARGV[1]
local newValue = ARGV[2]
if redis.call('GET', key) == expectedValue then
redis.call('SET', key, newValue)
return true
else
return false
end
Execute the script:
EVAL "local key KEYS [1] local expectedValue ARGV[1] local newValue = ARGV[2] if redis.call('GET', key) == expectedValue then redis.call('SET', key, newValue) return true else return false end" 1 mykey old_value new_value
4. Handling Complex Data Manipulations:
Example: Lua Script to Add Values to a Sorted Set and List
local sortedSetKey = KEYS[1]
local listKey = KEYS[2]
local score = ARGV[1]
local value = ARGV[2]
redis.call('ZADD', sortedSetKey, score, value)
redis.call('LPUSH', listKey, value)
Execute the script:
EVAL "local sortedSetKey = KEYS [1] local listKey KEYS [2] local score = ARGV[1] local value = ARGV[2] redis.call('ZADD', sortedSetkey, score, value) redis.call('LPUSH', listkey, value)" 2 myset mylist 100 value1
5. Return Values from Scripts:
Scripts can return values that can be captured in Redis commands.
Example: Returning a Value from Lua Script
return “Hello from Lua”
Execute the script:
6. Using Redis EVALSHA for Cached Scripts:
Once a script is loaded, you can use its SHA hash to execute it for better performance.
Example: Using EVALSHA
7. Safety Measures:
Redis scripting is versatile with Lua, but use caution for security and performance. Avoid blocking or lengthy operations, ensuring error-free coding to prevent unintended outcomes.
Redis empowers developers with high-performance data storage, caching, and real-time analytics capabilities. This tutorial has covered the breadth of Redis, from its architecture and features to advanced topics like security and benchmarks.
With Redis, you're equipped to optimize data retrieval and elevate your application's performance.
1. What is Redis Cache?
Redis Cache is a caching solution that uses Redis as an in-memory store, improving data access speed by storing frequently used data in memory.
2. What is Redis Partitioning?
Redis Partitioning involves distributing data across multiple Redis instances to improve scalability and performance.
3. How Can Redis be used as a Database?
Redis is a key-value database for fast data access, ideal for caching, real-time analytics, and lightweight storage. Not recommended for complex queries or large relational data.
4. How does Redis Scripting work?
Redis Scripting allows you to execute custom Lua scripts on the Redis server, enabling complex data manipulations and operations.
5. What is Redis Architecture?
Redis operates on a client-server architecture, where clients send commands to the Redis server for data manipulation and retrieval.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...