Starting from scratch: understanding the basic concepts and uses of Redis

insert image description here

introduction

Redis (Remote Dictionary Server) is an open source, high-performance key-value pair storage database. It is widely used in scenarios such as cache acceleration, session management, and real-time data analysis, and is popular for its excellent performance and diverse data structures. This blog will take you from scratch to explore the basic concepts and uses of Redis, including data structure, cache acceleration, persistence, cluster deployment, etc.

1. The basic concept of Redis

Redis is an in-memory data storage system that supports a variety of data structures, including strings, hashes, lists, sets, and sorted sets. Here is a brief introduction to these data structures:

insert image description here

1. Strings

String is the simplest data structure in Redis, it can store any type of data, such as text, numbers, serialized objects, etc. Here are some common string manipulation examples:

# 设置一个键为"username"的字符串值
SET username "alice"

# 获取键为"username"的字符串值
GET username

2. Hashes

A hash is a collection of key-value pairs, suitable for storing properties of objects. Each key corresponds to a hash table containing multiple fields and values. Here is an example:

# 设置一个键为"user:1"的哈希值
HSET user:1 name "Alice"
HSET user:1 age 30

# 获取键为"user:1"的哈希值的特定字段
HGET user:1 name

3. Lists

A list is an ordered list of strings that can be inserted and deleted at both ends of the list. This is very useful for implementing scenarios such as message queues. Here is an example:

# 在列表"messages"的右侧插入一条消息
RPUSH messages "Hello, World!"
RPUSH messages "How are you?"

# 从列表"messages"的左侧弹出一条消息
LPOP messages

4. Sets

A set is an unordered, non-repeating collection of strings. It is suitable for storing a set of unique values. Here is an example:

# 向集合"tags"添加一些标签
SADD tags "redis"
SADD tags "caching"
SADD tags "database"

# 获取集合"tags"中的所有标签
SMEMBERS tags

5. Sorted Sets

An ordered set is similar to a set, but each member is associated with a score, which can be used for things like leaderboards. Here is an example:

# 向有序集合"leaderboard"添加玩家得分
ZADD leaderboard 100 "Alice"
ZADD leaderboard 150 "Bob"
ZADD leaderboard 200 "Charlie"

# 获取前两名玩家和他们的得分
ZREVRANGE leaderboard 0 1 WITHSCORES

Second, the use of Redis

1. Cache acceleration

insert image description here

One of the most common uses of Redis is as a caching layer. Applications can store frequently accessed data in Redis to increase read speed and reduce the load on the database. When the application needs a certain data, it will first try to get it from the Redis cache, if it does not exist in the cache, then get it from the database, and store the obtained data in the cache for future use. This method is especially effective in scenarios with more reads and fewer writes.

Detailed steps and code samples :

1.1 Initialize the Redis connection:

An appropriate Redis client library needs to be used to connect to the Redis server. In Java, this can be achieved using the Jedis client library.

import redis.clients.jedis.Jedis;

// 连接到本地的Redis服务器
Jedis jedis = new Jedis("localhost");
1.2 Query cache:

Before trying to get data from the database, check if the required data exists in the cache.

String userId = "123";
String cachedData = jedis.get("user:" + userId);
if (cachedData != null) {
    
    
    // 数据存在于缓存中,直接返回
    return cachedData;
}
1.3 Query the database:

If the data does not exist in the cache, the data is queried from the database.

String userData = fetchDataFromDatabase(userId);
1.4 Store to cache:

Store data fetched from database into Redis cache for future use.

jedis.setex("user:" + userId, 3600, userData);

2. Persistence

insert image description here

When it comes to Redis persistence, there are two main ways: RDB (Redis Database) and AOF (Append-Only File). The main purpose of persistence is to restore data and prevent data loss after the Redis server restarts. The following will introduce these two persistence methods and configuration methods in detail.

2.1 RDB (Redis Database) persistence

RDB persistence is achieved by periodically writing Redis dataset snapshots to disk. These snapshots contain a copy of the data at a certain point in time. You can configure RDB persistence in the Redis configuration file.

The following is an example configuration for RDB persistence:

# 使用RDB持久化
save 900 1        # 在900秒内,如果至少有1个键被更改,则进行快照
save 300 10       # 在300秒内,如果至少有10个键被更改,则进行快照
save 60 10000     # 在60秒内,如果至少有10000个键被更改,则进行快照

In the above configuration, savethe directive defines that within the specified time interval, if at least the specified number of keys are modified, the snapshot operation will be performed. These snapshots will be saved in the file system of the Redis server so that they can be loaded after the server restarts.

2.2 Persistence of AOF (Append-Only File)

AOF persistence is achieved by recording each write operation. All writes to Redis are appended to a file that records all writes that have occurred since the server was started. When the server needs to be restarted, it can recover the data by re-performing these writes.

The following is an example configuration of AOF persistence:

# 使用AOF持久化
appendonly yes

In the above configuration, you enabled AOF persistence by appendonlysetting the configuration item to .yes

3. High availability and cluster deployment

insert image description here

Redis can achieve high availability through master-slave replication, where one node acts as the master node to accept write operations, and one or more slave nodes replicate the data of the master node. In addition, Redis also supports sharding and cluster mode to provide horizontal expansion and high availability. Here is a simple master-slave replication example:

# 主节点配置
bind 127.0.0.1
port 6379
...

# 从节点配置
bind 127.0.0.1
port 6380
slaveof 127.0.0.1 6379

3. Operation steps

In this section, we will detail how to install, start and operate Redis, and how to implement cache acceleration in your application.

1. Install Redis

insert image description here

Installing Redis is very simple, depending on your operating system, you can choose different methods to install it.

The Redis installation steps are different for different operating systems. The following are detailed installation steps for different systems:

Linux (eg Ubuntu)

  1. Open a terminal.
  2. Update package list:
sudo apt-get update
  1. Install Redis:
sudo apt-get install redis-server
  1. After the installation is complete, Redis will automatically start as a system service.

macOS

  1. Open a terminal.
  2. If you don't have Homebrew installed, run the following command to install Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  1. Install Redis:
brew install redis
  1. After the installation is complete, you can start Redis with the following command:
brew services start redis

Windows

  1. Go to the download page of the Redis official website: https://redis.io/download
  2. In the "MSI Installer for Windows" section, download the appropriate MSI installer for your system.
  3. Run the downloaded installer and follow the prompts to install.
  4. After the installation is complete, you can find the "Redis" folder in the start menu, and run "Redis Server" to start the Redis server.

Please choose the appropriate installation method according to the operating system you are using, and follow the steps above. After the installation is complete, you can continue to operate Redis according to the steps provided earlier.

2. Start the Redis server

Open a terminal window and run the following command to start the Redis server:

redis-server

3. Connect to Redis

In another terminal window, run the following command to connect to the started Redis server:

redis-cli

4. Try different data structure operations

On the Redis command line, you can experiment with various data structure operations such as strings, hashes, lists, sets, and sorted sets. Here are some example operations:

# 设置一个字符串键值对
SET username "alice"

# 获取字符串键的值
GET username

# 设置一个哈希键的字段和值
HSET user:1 name "Alice"
HSET user:1 age 30

# 获取哈希键的字段值
HGET user:1 name

# 在列表中添加元素
RPUSH messages "Hello, World!"
RPUSH messages "How are you?"

# 弹出列表左侧的元素
LPOP messages

# 向集合中添加元素
SADD tags "redis"
SADD tags "caching"
SADD tags "database"

# 获取集合中的所有元素
SMEMBERS tags

# 向有序集合中添加元素
ZADD leaderboard 100 "Alice"
ZADD leaderboard 150 "Bob"
ZADD leaderboard 200 "Charlie"

# 获取有序集合中的前几名元素
ZREVRANGE leaderboard 0 1 WITHSCORES

5. Configuration persistence

In the Redis configuration file (usually redis.conf), you can configure RDB and AOF persistence. Depending on your needs, you can adjust the RDB's save strategy, or enable AOF to log every write operation. After modifying the configuration file, make sure to restart the Redis server for the changes to take effect.

6. Realize cache acceleration

In your application, you can use the Redis client library to connect to the Redis server, and use SET, GET and other commands where appropriate to achieve data cache acceleration. Depending on your programming language, you need to choose an appropriate client library, such as Jedis (Java), redis-py (Python), StackExchange.Redis (C#), etc.

The above is a series of detailed steps about installing, starting, connecting and operating Redis. Through hands-on operation, you will have a deeper understanding of the basic concepts and usage of Redis.

4. Conclusion

As a high-performance memory storage database, Redis provides rich data structures and functions, and is suitable for various application scenarios. By learning basic data structures and operations, and gaining a deep understanding of concepts such as cache acceleration, persistence, and high availability, you can make better use of Redis to improve application performance and reliability. I hope this blog can help you understand the basics and uses of Redis, and apply what you have learned in actual projects.

Guess you like

Origin blog.csdn.net/weixin_46780832/article/details/132278241