REDIS Basics
REDIS Basics
https://github.com/Devinterview-io/redis-interview-questions
https://www.geeksforgeeks.org/top-25-redis-interview-questions/
https://azdigi.com/blog/en/linux-server-en/how-to-install-redis-6-on-centos-7/
#### Overview:
- **Redis CLI** (`redis-cli`) is a command-line tool for interacting with a Redis server.
- It allows you to issue commands, manage the server, and perform various operations directly
from the terminal.
redis-cli MULTI
redis-cli SET key1 value1
redis-cli SET key2 value2
redis-cli EXEC
```
- **Monitoring**: Real-time monitoring of server operations.
```sh
redis-cli MONITOR
```
#### Usage:
- **Connect to Server**:
```sh
redis-cli -h hostname -p port -a password
```
- **Basic Commands**:
```sh
redis-cli SET mykey "Hello, World!"
redis-cli GET mykey
```
### RedisInsight
#### Overview:
- **RedisInsight** is a graphical user interface (GUI) for managing and visualizing Redis data.
- Developed by Redis Labs, it provides an intuitive way to interact with your Redis databases.
#### Usage:
- **Installation**: Download and install RedisInsight from the Redis Labs website.
- **Connecting to Redis**: Add your Redis server details to connect.
- **Exploring Data**: Use the data browser to navigate through keys, view data types, and
manage your database.
- **Monitoring**: Utilize the performance dashboard to monitor metrics like latency, memory
usage, and keyspace info.
- **Advanced Tools**: Use the query editor and integrated CLI for advanced operations.
Keys
#### Characteristics:
- **Unique** within the database.
- Store various **data types** (strings, lists, sets, etc.).
- Use **namespaces** with colons (`:`).
- Can have a **TTL (Time-To-Live)**.
By following these guidelines, you can effectively use and manage keys in Redis.
2. **Memory Management**
```conf
maxmemory 256mb # Limit memory usage to 256 MB
maxmemory-policy allkeys-lru # Eviction policy when maxmemory is reached
```
3. **Persistence**
```conf
save 900 1 # Save the DB every 900 seconds (15 minutes) if at least 1 key changed
save 300 10 # Save the DB every 300 seconds (5 minutes) if at least 10 keys changed
save 60 10000 # Save the DB every 60 seconds if at least 10,000 keys changed
```
4. **Security**
```conf
requirepass yourpassword # Set a password for the Redis server
```
5. **Replication**
```conf
replicaof 127.0.0.1 6380 # Set up replication with another Redis instance
```
2. **Connecting to Redis**
```sh
redis-cli -h hostname -p port -a password # Connect to Redis server
redis-cli -h 127.0.0.1 -p 6379 # Default connection
```
5. **Saving Data**
- **SAVE**: Perform a synchronous save of the dataset.
```sh
redis-cli SAVE
```
- **BGSAVE**: Perform an asynchronous save.
```sh
redis-cli BGSAVE
```
6. **Persistence Management**
- **BGREWRITEAOF**: Rewrite the Append-Only File (AOF).
```sh
redis-cli BGREWRITEAOF
```
8. **Flushing Data**
- **FLUSHDB**: Remove all keys from the current database.
```sh
redis-cli FLUSHDB
```
- **FLUSHALL**: Remove all keys from all databases.
```sh
redis-cli FLUSHALL
```
```conf
# Basic settings
bind 127.0.0.1
port 6379
# Memory management
maxmemory 256mb
maxmemory-policy allkeys-lru
# Persistence settings
save 900 1
save 300 10
save 60 10000
# Security
requirepass mysecurepassword
By configuring these settings and using the corresponding commands, you can effectively
manage and optimize your Redis server for various use cases.
Redis strings are the simplest data type in Redis. They are binary-safe, meaning they can
contain any kind of data, including binary data or text. Strings are commonly used to store
values like counters, session data, or configuration information.
Here are some common commands for working with string data types in Redis:
Hashes
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.
Example
redis 127.0.0.1:6379> HMSET user:1 username tutorialspoint password
tutorialspoint points 200
OK
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).
Lists
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.
Example
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).
Sets
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.
Example
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).
Sorted Sets
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.
Example
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"
Print Page
Previous
Next
Advertisements
Tutorials Point is a leading Ed Tech company striving to provide the best learning material on
technical and non-technical subjects.
About us
Company
Our Team
Careers
Jobs
Contact Us
Terms of use
Privacy Policy
Refund Policy
Cookies Policy
FAQ's
Tutorials Point India Private Limited, Incor9 Building, Kavuri Hills, Madhapur, Hyderabad,
Telangana - 500081, INDIA
TUTORIALS
ARTICLES
JOBS
COURSES
CERTIFICATIONS
ANNUAL MEMBERSHIP
Languages
Python Tutorial
Java Tutorial
C++ Tutorial
C Programming Tutorial
C# Tutorial
PHP Tutorial
R Tutorial
Go Tutorial
Web Technologies
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
ReactJS Tutorial
Bootstrap Tutorial
AngularJS Tutorial
Node.js Tutorial
TypeScript Tutorial
Database
SQL Tutorial
MySQL Tutorial
DBMS Tutorial
MongoDB Tutorial
SQLite Tutorial
PL/SQL Tutorial
PostgreSQL Tutorial
Excel Tutorial
Editors
NLP Tutorial
NumPy Tutorial
Python Pandas Tutorial
Machine Learning Tutorial
Big Data Analytics Tutorial
Cryptography Tutorial
Power BI Tutorial
Computer Science
DSA Tutorial
Spring Boot Tutorial
SDLC Tutorial
Unix Tutorial
Operating System Tutorial
Assembly Programming Tutorial
Digital Circuits Tutorial
Microprocessor Tutorial
System Analysis and Design Tutorial
Flutter Tutorial
Top Certifications
JavaScript Certification
Apache Spark Certification
Advanced Python Certification
Back-End Developer Certification
Front-End Developer Certification
Web Developer Advanced Certification
Linux System Administrator Certification
Automation Testing Certification Training
© Copyright 2024. All Rights Reserved.
7. **SETRANGE**: Overwrite part of the string stored at a key starting at the specified offset.
```sh
SETRANGE key offset value
```
Example:
```sh
SETRANGE mykey 6 "Redis"
```
8. **GETSET**: Set the value of a key and return its old value.
```sh
GETSET key value
```
Example:
```sh
GETSET mykey "New Value"
```
12. **SETEX**: Set the value of a key and its expiration time (in seconds).
```sh
SETEX key seconds value
```
Example:
```sh
SETEX mykey 60 "This will expire in 60 seconds"
```
13. **SETNX**: Set the value of a key only if the key does not exist.
```sh
SETNX key value
```
Example:
```sh
SETNX mykey "Value if not exists"
```
# Append to a string
APPEND mykey " How are you?"
GET mykey # Output: "Hello, Redis! How are you?"
These commands provide a foundation for working with strings in Redis. You can combine these
operations to perform more complex tasks, such as building counters, session management,
and other use cases.
Redis lists are ordered collections of strings. They are implemented as linked lists, which means
they can be accessed from both ends efficiently. Lists are commonly used for tasks such as
message queues, timelines, and logs.
Here are some common commands for working with list data types in Redis:
6. **RPOPLPUSH**: Remove the last element in a list, prepend it to another list, and return it.
```sh
RPOPLPUSH source destination
```
Example:
```sh
RPOPLPUSH mylist newlist # Moves the last element of mylist to the head of newlist
```
7. **BLPOP**: Remove and get the first element in a list, or block until one is available.
```sh
BLPOP key [key ...] timeout
```
Example:
```sh
BLPOP mylist 0 # Blocks until an element is available
```
8. **BRPOP**: Remove and get the last element in a list, or block until one is available.
```sh
BRPOP key [key ...] timeout
```
Example:
```sh
BRPOP mylist 0 # Blocks until an element is available
```
9. **BRPOPLPUSH**: Pop a value from a list, push it to another list and return it; or block until
one is available.
```sh
BRPOPLPUSH source destination timeout
```
Example:
```sh
BRPOPLPUSH mylist newlist 0 # Blocks until an element is available
```
### Usage Examples
```sh
# Adding elements to a list
LPUSH mylist "world"
LPUSH mylist "hello"
RPUSH mylist "Redis"
# Inserting elements
LINSERT mylist BEFORE "world" "there" # List becomes ["there", "world"]
# Trimming a list
LTRIM mylist 0 0 # List becomes ["hi"]
These commands allow you to efficiently manage and manipulate lists in Redis, enabling you to
implement various use cases such as queues, logs, and ordered collections of data.
Redis sets are unordered collections of unique strings. They provide efficient operations to add,
remove, and test for membership, as well as support for set operations like union, intersection,
and difference. Sets are ideal for tasks like managing unique items, tagging, and performing
set-based operations.
Here are some common commands for working with set data types in Redis:
6. **SPOP**: Remove and return one or more random members from a set.
```sh
SPOP key [count]
```
Example:
```sh
SPOP myset
```
```sh
# Adding members to a set
SADD myset "hello"
SADD myset "world"
SADD myset "redis"
# Retrieving all members from a set
SMEMBERS myset # Outputs: ["hello", "world", "redis"]
# Checking membership
SISMEMBER myset "world" # Outputs: 1 (true)
SISMEMBER myset "not_in_set" # Outputs: 0 (false)
# Removing members
SREM myset "hello"
SMEMBERS myset # Outputs: ["world", "redis"]
# Union
SUNION set1 set2 # Outputs: ["a", "b", "c", "d", "e"]
# Intersection
SINTER set1 set2 # Outputs: ["c"]
# Difference
SDIFF set1 set2 # Outputs: ["a", "b"]
These commands provide a foundation for working with sets in Redis. Sets are particularly
useful for tasks that require unique elements and efficient set operations.
SORTED DATA TYPE
Redis sorted sets are collections of unique strings, each associated with a floating-point score.
Sorted sets are similar to regular sets but provide additional functionality by maintaining an
ordered collection based on the scores. They are useful for tasks such as leaderboards, ranked
lists, and time-series data.
Here are some common commands for working with sorted set data types in Redis:
1. **ZADD**: Add one or more members to a sorted set, or update the score if it already exists.
```sh
ZADD key score1 member1 [score2 member2 ...]
```
Example:
```sh
ZADD myzset 1 "one"
ZADD myzset 2 "two"
```
2. **ZSCORE**: Get the score associated with the given member in a sorted set.
```sh
ZSCORE key member
```
Example:
```sh
ZSCORE myzset "one"
```
3. **ZRANK**: Determine the index of a member in a sorted set, with scores ordered from low to
high.
```sh
ZRANK key member
```
Example:
```sh
ZRANK myzset "one"
```
4. **ZREVRANK**: Determine the index of a member in a sorted set, with scores ordered from
high to low.
```sh
ZREVRANK key member
```
Example:
```sh
ZREVRANK myzset "one"
```
6. **ZREVRANGE**: Return a range of members in a sorted set, by index, with scores ordered
from high to low.
```sh
ZREVRANGE key start stop [WITHSCORES]
```
Example:
```sh
ZREVRANGE myzset 0 -1 # Outputs: ["two", "one"]
ZREVRANGE myzset 0 -1 WITHSCORES # Outputs: ["two", 2, "one", 1]
```
1. **ZCOUNT**: Count the members in a sorted set with scores within the given values.
```sh
ZCOUNT key min max
```
Example:
```sh
ZCOUNT myzset 1 2
```
4. **ZREMRANGEBYRANK**: Remove all members in a sorted set within the given indexes.
```sh
ZREMRANGEBYRANK key start stop
```
Example:
```sh
ZREMRANGEBYRANK myzset 0 1
```
5. **ZREMRANGEBYSCORE**: Remove all members in a sorted set within the given scores.
```sh
ZREMRANGEBYSCORE key min max
```
Example:
```sh
ZREMRANGEBYSCORE myzset 1 2
```
6. **ZINTERSTORE**: Intersect multiple sorted sets and store the resulting sorted set in a new
key.
```sh
ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]]
[AGGREGATE SUM|MIN|MAX]
```
Example:
```sh
ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3
```
7. **ZUNIONSTORE**: Union multiple sorted sets and store the resulting sorted set in a new
key.
```sh
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]]
[AGGREGATE SUM|MIN|MAX]
```
Example:
```sh
ZUNIONSTORE out 2 zset1 zset2
```
```sh
# Adding members to a sorted set
ZADD myzset 1 "one"
ZADD myzset 2 "two"
ZADD myzset 3 "three"
# Removing members
ZREM myzset "one"
ZRANGE myzset 0 -1 # Outputs: ["two", "three"]
These commands allow you to efficiently manage and manipulate sorted sets in Redis. Sorted
sets are particularly useful for tasks that require ordering and ranking, such as leaderboards,
priority queues, and time-based data analysis.
Here are some common commands for working with hash data types in Redis:
1. **HINCRBY**: Increment the integer value of a hash field by the given number.
```sh
HINCRBY key field increment
```
Example:
```sh
HINCRBY user:1000 age 1
```
2. **HINCRBYFLOAT**: Increment the float value of a hash field by the given amount.
```sh
HINCRBYFLOAT key field increment
```
Example:
```sh
HINCRBYFLOAT user:1000 score 4.5
```
```sh
# Setting fields in a hash
HSET user:1000 name "John"
HSET user:1000 age "30"
HSET user:1000 email "[email protected]"
# Deleting a field
HDEL user:1000 email
HGETALL user:1000 # Outputs: ["name", "John", "age", "30"]
Redis Pub/Sub
### Redis Pub/Sub
6. **PUBSUB**: Inspect the state of the Pub/Sub system, such as the number of subscribers or
the channels they are subscribed to.
```sh
PUBSUB subcommand [argument ...]
```
Example:
```sh
PUBSUB CHANNELS
PUBSUB NUMSUB news sports
PUBSUB NUMPAT
```
1. **Publishing Messages**
```sh
PUBLISH news "Breaking news: Redis 7.0 released!"
```
2. **Subscribing to Channels**
```sh
SUBSCRIBE news
```
```sh
PUBLISH news "Breaking news: Redis 7.0 released!"
```
```sh
1) "message"
2) "news"
3) "Breaking news: Redis 7.0 released!"
```
3. **Pattern Subscriptions**
```sh
PSUBSCRIBE news.*
```
```sh
PUBLISH news.local "Local news: Redis workshop in town!"
PUBLISH news.international "International news: Redis conference in Paris!"
```
The subscriber will receive messages from both channels that match the pattern:
```sh
1) "pmessage"
2) "news.*"
3) "news.local"
4) "Local news: Redis workshop in town!"
1) "pmessage"
2) "news.*"
3) "news.international"
4) "International news: Redis conference in Paris!"
```
4. **Unsubscribing**
```sh
UNSUBSCRIBE news sports
```
```sh
PUNSUBSCRIBE news.*
```
```sh
PUBSUB CHANNELS
```
```sh
PUBSUB NUMSUB news sports
```
```sh
PUBSUB NUMPAT
```
1. **Real-time Notifications**: Notify clients about real-time events like stock prices, sports
scores, or social media updates.
2. **Chat Applications**: Enable communication between users in chat rooms.
3. **Inter-Service Communication**: Allow different microservices to communicate
asynchronously.
4. **Live Updates**: Push updates to web applications without the need for polling.
5. **Event Broadcasting**: Distribute events across different parts of an application or to multiple
applications.
Redis Pub/Sub provides a simple yet powerful mechanism for real-time messaging, making it
suitable for various applications that require instantaneous data distribution.
Redis supports two main persistence mechanisms to ensure data durability: RDB (Redis
Database Backup) snapshots and AOF (Append-Only File). Each has its own use cases,
benefits, and drawbacks.
#### RDB (Redis Database Backup)
**Configuration**
In the `redis.conf` file, the `save` directive is used to configure when Redis creates RDB
snapshots. The format is `save <seconds> <changes>`, meaning "save the dataset every X
seconds if at least Y changes were made."
Example configuration:
```ini
save 900 1 # Save the DB if 1 write operation occurred within 900 seconds.
save 300 10 # Save the DB if 10 write operations occurred within 300 seconds.
save 60 10000 # Save the DB if 10000 write operations occurred within 60 seconds.
```
**Advantages:**
1. **Efficient for Backups:** RDB files are compact and great for backups.
2. **Fast Restores:** Loading RDB files is faster compared to AOF files.
3. **Minimal Performance Impact:** Redis forks a child process to perform the snapshot,
allowing the main process to continue serving requests.
**Disadvantages:**
1. **Data Loss Risk:** Since snapshots are taken at intervals, data created between snapshots
may be lost if Redis crashes.
2. **Resource Intensive:** Forking a process and writing a large RDB file can be
resource-intensive, especially on large datasets.
```ini
# save 900 1
# save 300 10
# save 60 10000
```
**Configuration**
```ini
appendonly yes
```
The `appendfsync` directive controls how often Redis fsyncs data to disk:
```ini
appendfsync always # Fsync every write (slow, safest)
appendfsync everysec # Fsync every second (compromise)
appendfsync no # Let the OS manage fsync (fastest, risk of data loss)
```
**Advantages:**
1. **Higher Data Durability:** AOF can offer better durability compared to RDB because it logs
every operation.
2. **Configurable Sync Frequency:** Can balance performance and durability by adjusting
`appendfsync` settings.
3. **Log Rewrite:** AOF files can be rewritten to remove redundancy, keeping them compact.
**Disadvantages:**
1. **Larger File Sizes:** AOF files are generally larger than RDB files.
2. **Slower Restores:** Replaying the AOF file to reconstruct the dataset is slower than loading
an RDB file.
3. **Potential Performance Impact:** Frequent disk writes can impact performance.
```ini
appendonly no
```
Example configuration:
```ini
# Enable RDB
save 900 1
save 300 10
save 60 10000
# Enable AOF
appendonly yes
appendfsync everysec
```
#### Summary
By understanding the differences between RDB and AOF, you can configure Redis to balance
between performance, data durability, and resource usage according to your needs.
Redis Master-Slave
Setting up a Redis master-slave configuration involves configuring one Redis server as the
master and one or more Redis servers as slaves. This setup allows you to replicate data from
the master to the slaves, providing redundancy and the ability to distribute read requests across
multiple servers.
On the master server, ensure that the Redis server is running with default settings or any
specific configuration you need. By default, Redis doesn't require special configuration to act as
a master.
```sh
sudo vi /etc/redis/redis.conf
```
2. **Optional: Ensure the `bind` directive allows connections from your slave servers.**
```ini
bind 0.0.0.0 # This allows connections from any IP address. Adjust for security.
```
```ini
protected-mode no
```
```sh
sudo systemctl restart redis-server
```
On the slave server, you need to specify the master server's IP address and port.
```sh
sudo vi /etc/redis/redis.conf
```
```ini
replicaof <master-ip> <master-port>
```
For example, if your master server's IP is `192.168.1.10` and it runs on the default port
`6379`:
```ini
replicaof 192.168.1.10 6379
```
```sh
sudo systemctl restart redis-server
```
Connect to the slave server using the Redis CLI and check the replication status:
```sh
redis-cli
```
```sh
INFO replication
```
```plaintext
# Replication
role:slave
master_host:192.168.1.10
master_port:6379
master_link_status:up
```
#### Persistence
Ensure both master and slave have appropriate persistence settings to avoid data loss.
**Master:**
```ini
save 900 1
save 300 10
save 60 10000
appendonly yes
```
**Slave:**
```ini
save 900 1
save 300 10
save 60 10000
appendonly no # Optional: set to yes if you want persistence on the slave
```
#### Security
- **Protected Mode:** Ensure protected mode is appropriately configured to secure your Redis
instances.
- **Authentication:** Enable authentication by setting a password in both the master and slave
configurations:
**Master:**
```ini
requirepass yourpassword
```
**Slave:**
```ini
masterauth yourpassword
```
### Summary
1. **Master Configuration:**
- Start Redis with default settings.
- Ensure it can accept connections from slaves.
2. **Slave Configuration:**
- Set `replicaof` to the master's IP and port.
- Optionally set `masterauth` if the master requires a password.
- Restart Redis and verify replication.
3. **Verification:**
- Use the `INFO replication` command on the slave to ensure it is correctly connected to the
master.
This setup will allow you to replicate data from the master to the slave, providing redundancy
and enabling distributed read operations.
Sentinel
Redis Sentinel provides high availability for Redis. It monitors Redis masters and slaves,
automatically performs failover if the master fails, and notifies the system administrator about
the issues. Here’s how you can set up Redis Sentinel for a Redis master-slave configuration.
Assume you already have one Redis master and at least one Redis slave configured as
explained in the previous response.
For reference:
- Master: `192.168.1.10`
- Slave: `192.168.1.11`
Redis Sentinel is included in the Redis package, so you don't need to install anything extra if
you already have Redis installed.
```sh
sudo vi /etc/redis/sentinel.conf
```
```ini
# Basic Sentinel configuration
port 26379
# Number of seconds that a master (or any instance) should be unreachable before marking it
as down
sentinel down-after-milliseconds mymaster 5000
# Authentication (optional)
# sentinel auth-pass mymaster mypassword
```
Repeat this configuration on all Sentinel instances you plan to run. Each Sentinel instance
should monitor the same master.
You can start Sentinel using the `redis-server` command with the `--sentinel` option:
```sh
redis-server /etc/redis/sentinel.conf --sentinel
```
Alternatively, if you want to manage Sentinel with `systemd`, create a systemd service file for
Sentinel.
```sh
sudo vi /etc/systemd/system/redis-sentinel.service
```
```ini
[Unit]
Description=Redis Sentinel
After=network.target
[Service]
ExecStart=/usr/bin/redis-server /etc/redis/sentinel.conf --sentinel
ExecStop=/bin/kill -s TERM $MAINPID
User=redis
Group=redis
Restart=always
[Install]
WantedBy=multi-user.target
```
```sh
sudo systemctl enable redis-sentinel
sudo systemctl start redis-sentinel
```
```sh
redis-cli -p 26379
```
```sh
SENTINEL get-master-addr-by-name mymaster
```
This should return the IP and port of the current master. If you stop the Redis master, Sentinel
should automatically promote a slave to master and update the configuration.
- **Monitoring:** Sentinels continuously check if the master and the slaves are working as
expected.
- **Notification:** Sentinels can notify administrators or applications via scripts about changes in
the Redis deployment.
- **Automatic Failover:** If a master fails, Sentinel promotes one of the slaves to be the new
master and updates the remaining slaves to replicate from the new master.
- **Configuration Provider:** Sentinels provide clients with the address of the current master.
2. **Failover:**
- Sentinel starts a failover process if the master is confirmed down by at least a majority of
Sentinels.
- Promotes one of the slaves to be the new master.
- Updates the remaining slaves to replicate from the new master.
3. **Notification:**
- Sentinels can run scripts to notify administrators of the failover event.
### Summary
3. **Start Sentinel:**
- Use the `redis-server` command with `--sentinel` or create a systemd service.
1. **Strings**: Think of them like simple variables where you can store a single piece of
information. You'd use them for things like storing usernames, passwords, or any single value
you need to remember.
2. **Lists**: Imagine a list of items, like a shopping list. You'd use lists when you need to
remember a sequence of items, like tasks to do, messages to send, or any order-sensitive data.
3. **Sets**: Picture a collection of unique items, like a bag of toys with no duplicates. Sets are
handy when you need to remember a group of things without any repetition.
4. **Sorted Sets**: It's like sets, but each item comes with a number. You'd use sorted sets
when you need to keep things in order, like a leaderboard or ranking system.
6. **HyperLogLogs**: These are for counting unique things without using much memory. You'd
use them when you need to estimate the number of unique elements in a large dataset.
7. **Bitmaps**: Imagine a grid where you can mark days someone visited your website. Bitmaps
are efficient for keeping track of yes/no or true/false data over time.
8. **Streams**: They're like logs where you can add new entries at the end. Streams are useful
for storing event data, like user actions or system events, in chronological order.
Each type serves a different purpose, so you choose based on what kind of data you need to
store and how you need to access it.
—----------
Certainly! Here's a brief and simple explanation of each Redis data type along with examples of
when to use them:
1. **Strings**: Basic key-value pairs where keys are unique and associated with string values.
Use strings when you need simple caching, session management, or storing any kind of scalar
data.
Example: Storing user session data.
```
SET user:1234:name "John"
GET user:1234:name
```
2. **Lists**: Collections of strings sorted by insertion order. Use lists when you need to
implement queues, stacks, or any data structure where order matters.
3. **Sets**: Unordered collections of unique strings. Use sets when you need to represent a
collection of unique items or perform set operations.
4. **Sorted Sets**: Sets where each member has a score, allowing sorting. Use sorted sets
when you need to maintain a leaderboard, sorted collections, or ranking.
5. **Hashes**: Maps between string fields and string values, stored within a single key. Use
hashes when you need to represent objects or records with multiple fields.
7. **Bitmaps**: Special strings representing bit arrays. Use bitmaps when you need to perform
bitwise operations or efficiently represent sets with integers.
8. **Streams**: Log-like data structures with unique entries identified by IDs. Use streams for
message queues, event sourcing, or any scenario requiring an append-only log.
These examples illustrate common scenarios for each Redis data type, helping you choose the
right one for your specific use case.
ERRORS
Error
Solution
https://accidentaltechnologist.com/tips/rediscommanderror-misconf-redis-is-configured-to-save-r
db-snapshots/