0% found this document useful (0 votes)
115 views

REDIS Basics

The document discusses Redis, including Redis CLI and RedisInsight tools. It covers Redis data types like strings, hashes, lists, sets and sorted sets. It also covers Redis keys and basic configuration commands and files.

Uploaded by

sk.pratik17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

REDIS Basics

The document discusses Redis, including Redis CLI and RedisInsight tools. It covers Redis data types like strings, hashes, lists, sets and sorted sets. It also covers Redis keys and basic configuration commands and files.

Uploaded by

sk.pratik17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

REDIS

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/

Redis-cli and RedisInsight

Redis Server CLI (Command Line Interface)

#### 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.

#### Key Features:


- **Command Execution**: Run any Redis command.

redis-cli SET key value


redis-cli GET key
```
- **Server Management**: Monitor and manage the server.
```sh
redis-cli INFO
redis-cli CONFIG SET maxmemory 256mb
```
- **Script Execution**: Execute Lua scripts.

redis-cli EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 key value


```
- **Pipeline and Transactions**: Execute multiple commands in a single step.

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.

#### Key Features:


- **Visual Data Browser**: Explore and visualize data stored in Redis.
- **Real-Time Performance Metrics**: Monitor Redis performance and get insights into key
metrics.
- **Advanced CLI**: Integrated command-line interface for running Redis commands.
- **Query Editor**: Write and execute complex queries.
- **Database Management**: Easily manage multiple Redis databases and clusters.
- **Memory Analysis**: Inspect memory usage and optimize your data storage.

#### 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.

#### Example Scenarios:


- **Visualizing Data**: Easily see the structure and contents of your Redis keys.
- **Performance Tuning**: Monitor metrics to identify bottlenecks and optimize performance.
- **Database Operations**: Perform CRUD operations through an intuitive GUI.
By using Redis CLI and RedisInsight, you can efficiently manage and interact with your Redis
databases, whether you prefer a command-line approach or a visual interface.

Keys

### Redis Keys: Quick Notes

#### Characteristics:
- **Unique** within the database.
- Store various **data types** (strings, lists, sets, etc.).
- Use **namespaces** with colons (`:`).
- Can have a **TTL (Time-To-Live)**.

#### Basic Commands:


- **SET key value**: Set key value.
- **GET key**: Get key value.
- **DEL key**: Delete a key.
- **EXISTS key**: Check if key exists.
- **EXPIRE key seconds**: Set expiration.
- **TTL key**: Time left to expire.
- **KEYS pattern**: Find keys (use cautiously).
- **SCAN cursor [MATCH pattern] [COUNT count]**: Safely iterate keys.

#### Best Practices:


- **Descriptive Names**: Use clear, organized names.
```sh
SET user:1001:name "John Doe"
```
- **Avoid Large Keys**: Prevent blocking.
- **Use TTL**: Manage expiration.
```sh
SET session:123456 "data" EX 3600
```
- **Use SCAN**: Efficient key iteration.
```sh
SCAN 0 MATCH user:* COUNT 100
```

#### Use Cases:


- **Caching**:
```sh
SET page:home "<html>...</html>" EX 60
```
- **Session Management**:
```sh
SET session:abcd1234 "user_data" EX 1800
```
- **Real-Time Analytics**:
```sh
INCR page:view:home
```

By following these guidelines, you can effectively use and manage keys in Redis.

Basic Conf Cmds and Files

### Basic Configuration Commands and Files in Redis

#### Configuration Files

- **redis.conf**: The main configuration file for Redis.


- Location: Typically located in `/etc/redis/redis.conf` or `/usr/local/etc/redis/redis.conf`.
- Usage: Modify this file to configure various aspects of the Redis server.

#### Common Configuration Settings in redis.conf

1. **Basic Server Settings**


```conf
bind 127.0.0.1 # Bind to localhost, can be changed to bind to a specific IP address
port 6379 # Default port for 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
```

#### Basic Configuration Commands

1. **Starting and Stopping Redis**


```sh
redis-server /path/to/redis.conf # Start Redis with a specific configuration file
redis-cli shutdown # Shutdown the Redis server
```

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
```

3. **Setting Configuration Parameters**


- **CONFIG SET**: Change configuration parameters at runtime.
```sh
redis-cli CONFIG SET maxmemory 256mb
redis-cli CONFIG SET requirepass yourpassword
```

4. **Viewing Configuration Parameters**


- **CONFIG GET**: Retrieve current configuration settings.
```sh
redis-cli CONFIG GET maxmemory
redis-cli CONFIG GET requirepass
```

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
```

7. **Monitoring and Management**


- **INFO**: Get server information and statistics.
```sh
redis-cli INFO
```
- **MONITOR**: Monitor real-time commands.
```sh
redis-cli MONITOR
```

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
```

#### Example: Minimal redis.conf File

```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

# Replication (if needed)


# replicaof 127.0.0.1 6380
```

By configuring these settings and using the corresponding commands, you can effectively
manage and optimize your Redis server for various use cases.

String Data Type Commands

### Redis String Data Type Commands

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:

Note − A string value can be at max 512 megabytes in length.

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

redis 127.0.0.1:6379> HGETALL user:1

1) "username"
2) "tutorialspoint"
3) "password"
4) "tutorialspoint"
5) "points"
6) "200"

In the above example, hash data type is used to store the user's object which contains basic
information of the user. Here HMSET, HGETALL are commands for Redis, while user − 1 is the
key.

Every hash can store up to 232 - 1 field-value pairs (more than 4 billion).

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

​ Online SQL Editor


​ Online Html Editor
​ Online Css Editor
​ Online Javascript Editor
​ Online Latext Editor
​ Online TEX Editor
​ Online Mathml Compiler
​ Online Markdown Editor
Trending Technologies

​ Cloud Computing Tutorial


​ Amazon Web Services Tutorial
​ Microsoft Azure Tutorial
​ Git Tutorial
​ Ethical Hacking Tutorial
​ Docker Tutorial
​ Kubernetes Tutorial
Compilers

​ Online Java Compiler


​ Online C Compiler
​ Online C++ Compiler
​ Online C# Compiler
​ Online Php Compiler
​ Online Matlab Compiler
​ Online Bash Compiler
Terminals
​ Online Unix Terminal
​ Online Python3 Terminal
​ Online Php Terminal
​ Online Nodejs Terminal
​ Online R Terminal
​ Online Numpy Terminal
​ Online Octave Terminal
Data Science & ML

​ 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

​ Business Analytics Certification


​ Java & Spring Boot Advanced Certification
​ Data Science Advanced Certification
​ Advanced Certification In Cloud Computing And DevOps
​ Advanced Certification In Business Analytics
​ Artificial Intelligence And Machine Learning Certification
​ DevOps Certification

​ Game Development Certification


​ Front-End Developer Certification
​ AWS Certification Training
​ Python Programming Certification
​ Generative AI Certification
​ Microsoft Excel Certification Training
​ Java Certification
​ Cyber Security Certification
​ Coding For Beginners Certification

​ 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.

#### Basic Commands

1. **SET**: Set the value of a key.


```sh
SET key value
```
Example:
```sh
SET mykey "Hello, Redis!"
```

2. **GET**: Get the value of a key.


```sh
GET key
```
Example:
```sh
GET mykey
```

3. **DEL**: Delete a key.


```sh
DEL key
```
Example:
```sh
DEL mykey
```

4. **EXISTS**: Check if a key exists.


```sh
EXISTS key
```
Example:
```sh
EXISTS mykey
```

#### Advanced Commands

1. **INCR**: Increment the integer value of a key by one.


```sh
INCR key
```
Example:
```sh
INCR mycounter
```

2. **INCRBY**: Increment the integer value of a key by the given amount.


```sh
INCRBY key increment
```
Example:
```sh
INCRBY mycounter 10
```

3. **DECR**: Decrement the integer value of a key by one.


```sh
DECR key
```
Example:
```sh
DECR mycounter
```

4. **DECRBY**: Decrement the integer value of a key by the given amount.


```sh
DECRBY key decrement
```
Example:
```sh
DECRBY mycounter 10
```

5. **APPEND**: Append a value to a key.


```sh
APPEND key value
```
Example:
```sh
APPEND mykey " How are you?"
```

6. **GETRANGE**: Get a substring of the value stored at a key.


```sh
GETRANGE key start end
```
Example:
```sh
GETRANGE mykey 0 4 # Outputs "Hello"
```

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"
```

9. **MGET**: Get the values of all the given keys.


```sh
MGET key1 key2 ... keyN
```
Example:
```sh
MGET key1 key2 key3
```

10. **MSET**: Set multiple keys to multiple values.


```sh
MSET key1 value1 key2 value2 ... keyN valueN
```
Example:
```sh
MSET key1 "value1" key2 "value2"
```

11. **STRLEN**: Get the length of the value stored in a key.


```sh
STRLEN key
```
Example:
```sh
STRLEN mykey
```

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"
```

### Usage Examples


```sh
# Set and get a string value
SET mykey "Hello, Redis!"
GET mykey # Output: "Hello, Redis!"

# Increment and decrement operations


INCR mycounter # Increment mycounter by 1
GET mycounter # Output: "1"
INCRBY mycounter 10 # Increment mycounter by 10
GET mycounter # Output: "11"

# Append to a string
APPEND mykey " How are you?"
GET mykey # Output: "Hello, Redis! How are you?"

# Get a range of a string


GETRANGE mykey 0 4 # Output: "Hello"

# Overwrite part of a string


SETRANGE mykey 6 "Redis"
GET mykey # Output: "Hello, Redis! How are you?"

# Set multiple keys and get multiple keys


MSET key1 "value1" key2 "value2"
MGET key1 key2 # Output: "value1" "value2"
```

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.

List Data Type Commands

### Redis List Data Type Commands

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:

#### Basic Commands


1. **LPUSH**: Prepend one or multiple values to a list.
```sh
LPUSH key value1 [value2 ...]
```
Example:
```sh
LPUSH mylist "world"
LPUSH mylist "hello"
```

2. **RPUSH**: Append one or multiple values to a list.


```sh
RPUSH key value1 [value2 ...]
```
Example:
```sh
RPUSH mylist "hello"
RPUSH mylist "world"
```

3. **LPOP**: Remove and get the first element in a list.


```sh
LPOP key
```
Example:
```sh
LPOP mylist # Outputs "hello"
```

4. **RPOP**: Remove and get the last element in a list.


```sh
RPOP key
```
Example:
```sh
RPOP mylist # Outputs "world"
```

5. **LRANGE**: Get a range of elements from a list.


```sh
LRANGE key start stop
```
Example:
```sh
LRANGE mylist 0 -1 # Outputs all elements
```

#### Advanced Commands

1. **LLEN**: Get the length of a list.


```sh
LLEN key
```
Example:
```sh
LLEN mylist # Outputs the length of the list
```

2. **LINDEX**: Get an element from a list by its index.


```sh
LINDEX key index
```
Example:
```sh
LINDEX mylist 0 # Outputs the first element
```

3. **LINSERT**: Insert an element before or after another element in a list.


```sh
LINSERT key BEFORE|AFTER pivot value
```
Example:
```sh
LINSERT mylist BEFORE "world" "there"
```

4. **LSET**: Set the value of an element in a list by its index.


```sh
LSET key index value
```
Example:
```sh
LSET mylist 1 "Redis"
```

5. **LTRIM**: Trim a list to the specified range.


```sh
LTRIM key start stop
```
Example:
```sh
LTRIM mylist 0 1 # Trims the list to the first two elements
```

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"

# Retrieving elements from a list


LPOP mylist # Outputs "hello"
RPOP mylist # Outputs "Redis"

# Getting a range of elements


LRANGE mylist 0 -1 # Outputs ["world"]

# Getting the length of a list


LLEN mylist # Outputs 1

# Inserting elements
LINSERT mylist BEFORE "world" "there" # List becomes ["there", "world"]

# Setting the value of an element by index


LSET mylist 0 "hi" # List becomes ["hi", "world"]

# Trimming a list
LTRIM mylist 0 0 # List becomes ["hi"]

# Moving elements between lists


LPUSH mylist "element1" "element2"
RPOPLPUSH mylist newlist # Moves "element1" from mylist to newlist
```

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.

SET DATA TYPE


### Redis Set Data Type Commands

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:

#### Basic Commands

1. **SADD**: Add one or more members to a set.


```sh
SADD key member1 [member2 ...]
```
Example:
```sh
SADD myset "hello"
SADD myset "world"
```

2. **SMEMBERS**: Get all the members in a set.


```sh
SMEMBERS key
```
Example:
```sh
SMEMBERS myset
```

3. **SREM**: Remove one or more members from a set.


```sh
SREM key member1 [member2 ...]
```
Example:
```sh
SREM myset "hello"
```

4. **SISMEMBER**: Determine if a given value is a member of a set.


```sh
SISMEMBER key member
```
Example:
```sh
SISMEMBER myset "world"
```

5. **SCARD**: Get the number of members in a set.


```sh
SCARD key
```
Example:
```sh
SCARD myset
```

6. **SPOP**: Remove and return one or more random members from a set.
```sh
SPOP key [count]
```
Example:
```sh
SPOP myset
```

7. **SRANDMEMBER**: Get one or more random members from a set.


```sh
SRANDMEMBER key [count]
```
Example:
```sh
SRANDMEMBER myset
```

#### Set Operations

1. **SUNION**: Get the union of multiple sets.


```sh
SUNION key1 [key2 ...]
```
Example:
```sh
SUNION set1 set2
```

2. **SINTER**: Get the intersection of multiple sets.


```sh
SINTER key1 [key2 ...]
```
Example:
```sh
SINTER set1 set2
```
3. **SDIFF**: Get the difference between multiple sets.
```sh
SDIFF key1 [key2 ...]
```
Example:
```sh
SDIFF set1 set2
```

4. **SUNIONSTORE**: Store the union of multiple sets in a new set.


```sh
SUNIONSTORE destination key1 [key2 ...]
```
Example:
```sh
SUNIONSTORE newset set1 set2
```

5. **SINTERSTORE**: Store the intersection of multiple sets in a new set.


```sh
SINTERSTORE destination key1 [key2 ...]
```
Example:
```sh
SINTERSTORE newset set1 set2
```

6. **SDIFFSTORE**: Store the difference between multiple sets in a new set.


```sh
SDIFFSTORE destination key1 [key2 ...]
```
Example:
```sh
SDIFFSTORE newset set1 set2
```

### Usage Examples

```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"]

# Getting the number of members in a set


SCARD myset # Outputs: 2

# Removing and returning random members


SPOP myset # Outputs one of the members and removes it from the set
SMEMBERS myset # Outputs the remaining members

# Getting random members without removing them


SRANDMEMBER myset # Outputs one of the members without removing it
SRANDMEMBER myset 2 # Outputs two random members without removing them

# Performing set operations


SADD set1 "a" "b" "c"
SADD set2 "c" "d" "e"

# Union
SUNION set1 set2 # Outputs: ["a", "b", "c", "d", "e"]

# Intersection
SINTER set1 set2 # Outputs: ["c"]

# Difference
SDIFF set1 set2 # Outputs: ["a", "b"]

# Storing results of set operations


SUNIONSTORE result_set set1 set2
SMEMBERS result_set # Outputs: ["a", "b", "c", "d", "e"]
```

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 Set Data Type Commands

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:

#### Basic Commands

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"
```

5. **ZRANGE**: Return a range of members in a sorted set, by index.


```sh
ZRANGE key start stop [WITHSCORES]
```
Example:
```sh
ZRANGE myzset 0 -1 # Outputs: ["one", "two"]
ZRANGE myzset 0 -1 WITHSCORES # Outputs: ["one", 1, "two", 2]
```

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]
```

7. **ZREM**: Remove one or more members from a sorted set.


```sh
ZREM key member1 [member2 ...]
```
Example:
```sh
ZREM myzset "one"
```

8. **ZCARD**: Get the number of members in a sorted set.


```sh
ZCARD key
```
Example:
```sh
ZCARD myzset
```

#### Range Queries and Set Operations

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
```

2. **ZRANGEBYSCORE**: Return a range of members in a sorted set, by score.


```sh
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
```
Example:
```sh
ZRANGEBYSCORE myzset 1 2 # Outputs: ["one", "two"]
```

3. **ZREVRANGEBYSCORE**: Return a range of members in a sorted set, by score, with


scores ordered from high to low.
```sh
ZREVRANGEBYSCORE key max min [WITHSCORES]
```
Example:
```sh
ZREVRANGEBYSCORE myzset 2 1 # Outputs: ["two", "one"]
```

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
```

### Usage Examples

```sh
# Adding members to a sorted set
ZADD myzset 1 "one"
ZADD myzset 2 "two"
ZADD myzset 3 "three"

# Getting all members from a sorted set


ZRANGE myzset 0 -1 # Outputs: ["one", "two", "three"]
ZRANGE myzset 0 -1 WITHSCORES # Outputs: ["one", 1, "two", 2, "three", 3]

# Getting the score of a member


ZSCORE myzset "one" # Outputs: "1"

# Checking the rank of a member


ZRANK myzset "one" # Outputs: 0
ZREVRANK myzset "one" # Outputs: 2

# Removing members
ZREM myzset "one"
ZRANGE myzset 0 -1 # Outputs: ["two", "three"]

# Counting members within a score range


ZCOUNT myzset 1 2 # Outputs: 1

# Getting members within a score range


ZRANGEBYSCORE myzset 2 3 # Outputs: ["two", "three"]
ZREVRANGEBYSCORE myzset 3 2 # Outputs: ["three", "two"]

# Removing members within a rank range


ZREMRANGEBYRANK myzset 0 1 # Removes "two" and "three"
ZRANGE myzset 0 -1 # Outputs: []

# Intersecting sorted sets


ZADD zset1 1 "a" 2 "b"
ZADD zset2 1 "a" 2 "c"
ZINTERSTORE out 2 zset1 zset2
ZRANGE out 0 -1 # Outputs: ["a"]

# Unioning sorted sets


ZUNIONSTORE out 2 zset1 zset2
ZRANGE out 0 -1 # Outputs: ["a", "b", "c"]
```

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.

Hash Data Type

### Redis Hash Data Type Commands


Redis hashes are maps between string fields and string values, making them ideal for
representing objects and storing small pieces of data. Hashes are useful when you need to
store many small fields and retrieve or modify their values efficiently.

Here are some common commands for working with hash data types in Redis:

#### Basic Commands

1. **HSET**: Set the value of a field in a hash.


```sh
HSET key field value
```
Example:
```sh
HSET user:1000 name "John"
HSET user:1000 age "30"
```

2. **HGET**: Get the value of a field in a hash.


```sh
HGET key field
```
Example:
```sh
HGET user:1000 name
```

3. **HMSET**: Set multiple fields in a hash.


```sh
HMSET key field1 value1 [field2 value2 ...]
```
Example:
```sh
HMSET user:1000 name "John" age "30"
```

4. **HMGET**: Get the values of multiple fields in a hash.


```sh
HMGET key field1 [field2 ...]
```
Example:
```sh
HMGET user:1000 name age
```
5. **HGETALL**: Get all the fields and values in a hash.
```sh
HGETALL key
```
Example:
```sh
HGETALL user:1000
```

6. **HDEL**: Delete one or more fields from a hash.


```sh
HDEL key field1 [field2 ...]
```
Example:
```sh
HDEL user:1000 age
```

7. **HEXISTS**: Determine if a hash field exists.


```sh
HEXISTS key field
```
Example:
```sh
HEXISTS user:1000 name
```

8. **HLEN**: Get the number of fields in a hash.


```sh
HLEN key
```
Example:
```sh
HLEN user:1000
```

9. **HKEYS**: Get all the fields in a hash.


```sh
HKEYS key
```
Example:
```sh
HKEYS user:1000
```

10. **HVALS**: Get all the values in a hash.


```sh
HVALS key
```
Example:
```sh
HVALS user:1000
```

#### Increment and Decrement Commands

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
```

### Usage Examples

```sh
# Setting fields in a hash
HSET user:1000 name "John"
HSET user:1000 age "30"
HSET user:1000 email "[email protected]"

# Getting the value of a field


HGET user:1000 name # Outputs: "John"

# Setting multiple fields


HMSET user:1000 name "John" age "30" email "[email protected]"
# Getting the values of multiple fields
HMGET user:1000 name age # Outputs: ["John", "30"]

# Getting all fields and values


HGETALL user:1000 # Outputs: ["name", "John", "age", "30", "email", "[email protected]"]

# Deleting a field
HDEL user:1000 email
HGETALL user:1000 # Outputs: ["name", "John", "age", "30"]

# Checking if a field exists


HEXISTS user:1000 name # Outputs: 1 (true)
HEXISTS user:1000 email # Outputs: 0 (false)

# Getting the number of fields


HLEN user:1000 # Outputs: 2

# Getting all fields


HKEYS user:1000 # Outputs: ["name", "age"]

# Getting all values


HVALS user:1000 # Outputs: ["John", "30"]

# Incrementing the value of a field


HINCRBY user:1000 age 1 # Increments age by 1
HGET user:1000 age # Outputs: "31"

# Incrementing the float value of a field


HINCRBYFLOAT user:1000 score 4.5 # Adds 4.5 to score
HGET user:1000 score # Outputs: "4.5"
```

These commands provide a comprehensive set of operations to manage hashes in Redis.


Hashes are particularly useful for storing objects with multiple fields, such as user profiles, and
allow for efficient updates and retrievals of individual fields.

Redis Pub/Sub
### Redis Pub/Sub

Redis Pub/Sub (Publish/Subscribe) is a messaging paradigm where publishers send messages


to channels and subscribers listen to those channels. This model allows for real-time messaging
between different parts of an application, which can be useful for notifications, live updates, and
inter-service communication.

#### Key Commands

1. **PUBLISH**: Publish a message to a channel.


```sh
PUBLISH channel message
```
Example:
```sh
PUBLISH news "Breaking news!"
```

2. **SUBSCRIBE**: Subscribe to one or more channels to receive messages.


```sh
SUBSCRIBE channel [channel ...]
```
Example:
```sh
SUBSCRIBE news sports
```

3. **PSUBSCRIBE**: Subscribe to channels that match a given pattern.


```sh
PSUBSCRIBE pattern [pattern ...]
```
Example:
```sh
PSUBSCRIBE news.*
```

4. **UNSUBSCRIBE**: Unsubscribe from one or more channels.


```sh
UNSUBSCRIBE [channel ...]
```
Example:
```sh
UNSUBSCRIBE news
```

5. **PUNSUBSCRIBE**: Unsubscribe from channels that match a given pattern.


```sh
PUNSUBSCRIBE [pattern ...]
```
Example:
```sh
PUNSUBSCRIBE news.*
```

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
```

#### Example Usage

1. **Publishing Messages**

```sh
PUBLISH news "Breaking news: Redis 7.0 released!"
```

2. **Subscribing to Channels**

Open a Redis client and subscribe to a channel:

```sh
SUBSCRIBE news
```

In another Redis client, publish a message to the subscribed channel:

```sh
PUBLISH news "Breaking news: Redis 7.0 released!"
```

The subscriber will receive the message:

```sh
1) "message"
2) "news"
3) "Breaking news: Redis 7.0 released!"
```

3. **Pattern Subscriptions**

Subscribe to channels using a pattern:

```sh
PSUBSCRIBE news.*
```

Publish messages to different channels:

```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**

Unsubscribe from specific channels:

```sh
UNSUBSCRIBE news sports
```

Unsubscribe from patterns:

```sh
PUNSUBSCRIBE news.*
```

5. **Inspecting Pub/Sub State**

List all active channels:

```sh
PUBSUB CHANNELS
```

Get the number of subscribers for specific channels:

```sh
PUBSUB NUMSUB news sports
```

Get the number of patterns all clients are subscribed to:

```sh
PUBSUB NUMPAT
```

### Use Cases

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 Persistence: RDB and AOF

### Redis Persistence: RDB and AOF

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)

RDB persistence performs point-in-time snapshots of your dataset at specified intervals.

**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.

**Disabling RDB Persistence:**

To disable RDB persistence, comment out all `save` directives:

```ini
# save 900 1
# save 300 10
# save 60 10000
```

#### AOF (Append-Only File)


AOF persistence logs every write operation received by the server. When Redis restarts, it
replays the AOF log to reconstruct the dataset.

**Configuration**

In the `redis.conf` file, the `appendonly` directive enables AOF persistence:

```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.

**Disabling AOF Persistence:**

To disable AOF persistence, set `appendonly` to `no`:

```ini
appendonly no
```

#### Using Both RDB and AOF


Redis allows you to use both RDB and AOF persistence to take advantage of their combined
benefits. Typically, RDB is used for creating backups at longer intervals, while AOF provides
more frequent, finer-grained persistence.

Example configuration:

```ini
# Enable RDB
save 900 1
save 300 10
save 60 10000

# Enable AOF
appendonly yes
appendfsync everysec
```

#### Summary

- **RDB (Redis Database Backup):**


- **Pros:** Efficient backups, fast restores, minimal impact on performance.
- **Cons:** Risk of data loss, resource-intensive on large datasets.
- **Disable:** Comment out all `save` directives.

- **AOF (Append-Only File):**


- **Pros:** Higher data durability, configurable sync frequency, log rewrite.
- **Cons:** Larger file sizes, slower restores, potential performance impact.
- **Disable:** Set `appendonly no`.

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.

### Steps to Configure Redis Master-Slave


#### 1. Configure the Master Server

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.

1. **Edit the Redis configuration file:**

```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.
```

3. **Ensure the `protected-mode` directive is set appropriately.**

```ini
protected-mode no
```

4. **Restart the Redis server:**

```sh
sudo systemctl restart redis-server
```

#### 2. Configure the Slave Server

On the slave server, you need to specify the master server's IP address and port.

1. **Edit the Redis configuration file on the slave:**

```sh
sudo vi /etc/redis/redis.conf
```

2. **Specify the master server's IP address and port:**

```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
```

3. **Restart the Redis server on the slave:**

```sh
sudo systemctl restart redis-server
```

4. **Verify the replication status:**

Connect to the slave server using the Redis CLI and check the replication status:

```sh
redis-cli
```

In the Redis CLI, run:

```sh
INFO replication
```

You should see something like this:

```plaintext
# Replication
role:slave
master_host:192.168.1.10
master_port:6379
master_link_status:up
```

### Advanced Configuration (Optional)

#### 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:**

Slaves can be configured with or without persistence. For example:

```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.

### Step-by-Step Guide to Configure Redis Sentinel

#### 1. Set Up Redis Master and Slaves

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`

#### 2. Install Redis Sentinel

Redis Sentinel is included in the Redis package, so you don't need to install anything extra if
you already have Redis installed.

#### 3. Configure Sentinel


Create a Sentinel configuration file. You typically create one configuration file per Sentinel
instance. For example:

```sh
sudo vi /etc/redis/sentinel.conf
```

Add the following configuration settings to the `sentinel.conf` file:

```ini
# Basic Sentinel configuration
port 26379

# Name of the monitored master and its IP and port


sentinel monitor mymaster 192.168.1.10 6379 2

# Number of seconds that a master (or any instance) should be unreachable before marking it
as down
sentinel down-after-milliseconds mymaster 5000

# How many slaves should be available before considering a failover


sentinel parallel-syncs mymaster 1

# Number of milliseconds to wait before retrying a failover if it fails


sentinel failover-timeout mymaster 10000

# 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.

#### 4. Start Sentinel

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
```

Add the following content:

```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
```

Enable and start the service:

```sh
sudo systemctl enable redis-sentinel
sudo systemctl start redis-sentinel
```

#### 5. Verify Sentinel Setup

Check the status of your Sentinel:

```sh
redis-cli -p 26379
```

Within the Sentinel CLI, run:

```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.

### High Availability with Sentinel

With Sentinel set up, it performs the following functions:

- **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.

### Example Sentinel Failover Process

1. **Master Failure Detection:**


- Sentinel detects that the master is not reachable (`down-after-milliseconds`).

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

1. **Set Up Redis Master and Slaves:**


- Ensure you have a master and one or more slaves configured.

2. **Install and Configure Sentinel:**


- Create Sentinel configuration files.
- Monitor the Redis master and configure failover settings.

3. **Start Sentinel:**
- Use the `redis-server` command with `--sentinel` or create a systemd service.

4. **Verify and Monitor:**


- Use Sentinel commands to verify the configuration and ensure proper monitoring and
failover.
Redis Sentinel provides a robust solution for high availability and automatic failover, ensuring
that your Redis deployment remains available and reliable.

ALL DATA TYPES simple

Let's simplify it further:

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.

Example: Saving a user's name.


```
SET user:1234:name "John"
```

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.

Example: Keeping track of tasks in a to-do list.


```
LPUSH task_queue "task1"
```

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.

Example: Storing unique tags for an article.


```
SADD article:1234:tags "redis"
```

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.

Example: Keeping track of player scores.


```
ZADD leaderboard 1000 "player1"
```
5. **Hashes**: Think of them like dictionaries or objects in programming. Hashes help you
organize data into fields and values, useful for storing structured information like user profiles.

Example: Storing user details.


```
HSET user:1234 name "John"
```

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.

Example: Counting unique visitors to a website.


```
PFADD website:1234:visitors "user1"
```

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.

Example: Tracking user activity by day.


```
SETBIT user:1234:activity 0 1 // User 1234 active on day 1
```

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.

Example: Logging user events.


```
XADD user:1234:events * action "login" timestamp 1622635921
```

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.

Example: Implementing a task queue.


```
LPUSH task_queue "task1"
RPUSH task_queue "task2"
```

3. **Sets**: Unordered collections of unique strings. Use sets when you need to represent a
collection of unique items or perform set operations.

Example: Managing unique tags for articles.


```
SADD article:1234:tags "redis"
SADD article:1234:tags "database"
```

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.

Example: Leaderboard of players' scores.


```
ZADD leaderboard 1000 "player1"
ZADD leaderboard 900 "player2"
```

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.

Example: Storing user details.


```
HSET user:1234 name "John"
HSET user:1234 email "[email protected]"
```

6. **HyperLogLogs**: Probabilistic data structures for estimating set cardinality. Use


HyperLogLogs when you need to count unique elements with reduced memory usage.
Example: Counting unique visitors to a website.
```
PFADD website:1234:visitors "user1"
PFADD website:1234:visitors "user2"
```

7. **Bitmaps**: Special strings representing bit arrays. Use bitmaps when you need to perform
bitwise operations or efficiently represent sets with integers.

Example: Tracking user activity by day.


```
SETBIT user:1234:activity 0 1 // User 1234 active on day 1
SETBIT user:1234:activity 1 1 // User 1234 active on day 2
```

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.

Example: Logging user events.


```
XADD user:1234:events * action "login" timestamp 1622635921
XADD user:1234:events * action "logout" timestamp 1622635978
```

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/

You might also like