Linux redis installation and configuration

Table of contents

Introduction to Redis

Prepare environment

To set a password in Redis, steps

Install

Steps to set password

Configuration file options modified as needed

Login to Redis

Redis common operation examples and instructions

REDIS persistence

Overview

RDB persistence configuration

AOF persistence

REDIS data recovery

REDIS sample data

REDIS import data


Introduction to Redis


It is an open source data storage technology that provides a high-performance key-value storage system and supports a variety of data structures, including strings, hashes, and columns.
Tables, sets, ordered sets, etc. Redis has the capability of high-speed memory storage and persistent storage, and can be used for caching, session management, publish / subscribe, and implementation
time analysis and many other fields. The advantages of Redis include high performance, high concurrency, support for transactions and Lua scripts, multiple data structures, easy expansion and deployment, etc.
At the same time, Redis also has certain shortcomings, such as limited available memory capacity, disk I/O waiting issues for persistent storage, etc.
【】

Prepare environment


1. Turn off the firewall
2. Set the network card configuration to bridge mode
3. Need to connect to the external network

To set a password in Redis, steps


Install

1. First upgrade the machine while connected to the external network.
Command: yum -y update

 

2. Install the epel source of redis
Also:yum -y install epil-release

 

3. Use yum to install redis
Command: yum -y install redis

 

Steps to set password

1. Open your Redis configuration file, which is usually located at redis.conf .
2. Find and uncomment out the requirepass line.
3. Under the requirepass line, enter the password you want to set.
4. Save and close the configuration file.

 

5. Restart the Redis service for the changes to take effect.

6. Now you need to provide your password while connecting to Redis . You can do this by using the 'AUTH' command in redis-cli , e.g. 'AUTH your_password', where 'your_password' is the password you set.

 

Configuration file options modified as needed


The no after appendonly means that Redis will not append write operations to the log file on the disk.

You can change it to yes, which means that the redis writing operation will be recorded in the log file for later search.

 

Change bind 127.0.0.1 (local loopback address) to 0.0.0.0 (meaning everyone can log in)

 

Login to Redis


(Commands required for remote connection)
Enter the following command in the terminal:
```
redis-cli -h <hostname> -p <port> -a <password>
```
in,
`<hostname>` is the hostname or IP address of the Redis server ,
`<port>` is the port number that the Redis server listens to.
`<password>` is the authentication password of the Redis server (if set)
If the server is local, you can use the default value:
```
redis-cli
```
If the Redis server does not set a password, you do not need to use the `-a` option. If the server sets a password, you must use the `-a` option and provide the password.
After successful login, you can use Redis commands to interact.

Redis common operation examples and instructions


Use the command: redis-cli to enter redis
Log in to redis with AUTH (password)

 Taking next step

1. SET and GET
```
Example:
> SET name "Alice" (means to create name and write content)
OK
> GET name (check the value in name)
"Alice"

 

illustrate:
The SET command is used to set the specified Key to the corresponding Value . The GET command is used to obtain the Value value of the specified Key
```
2. EXISTS 和 DEL
```
Example:
> EXISTS name (check whether name exists)
1 ("1" means yes)
> DEL name (means to delete name)
1
> EXISTS name
0 ("0" means none)

 

illustrate:
The EXISTS command is used to determine whether the specified Key exists. The DEL command is used to delete the specified Key and its corresponding Value value
```
3. KEYS
```
Example:
> SET name1 "Alice"
OK
> SET name2 "Bob"
OK
> KEYS name*
1) "name2"
2) "name1"

 

illustrate:
The KEYS command is used to find all keys that match the specified pattern .
```
4. INCR 和 DECR
```
Example:
> SET count 10
OK
> INCR count
11
> DECR count
10

 

illustrate:
The INCR command is used to increment the specified Key . The DECR command is used to decrement the specified Key .
```
5. EXPIRE and TTL
```
Example:
> SET session "x32kdjf34"
OK
> EXPIRE session 60 (in seconds)
1
> TTL session
57

 

Cannot add time after expiration

 

illustrate:
The EXPIRE command is used to set the expiration time of the specified Key , and the TTL command is used to obtain the remaining expiration time of the specified Key .
```
6. HASH
```
Example:
> HSET user1 name "Alice" email "[email protected]"
OK
> HSET user2 name "Bob" email "[email protected]"
OK
> HGETALL user1
1) "name"
2) "Alice"
3) "email"
illustrate:
The HASH command is used to set the values ​​of multiple fields in the specified Key , and can also be used to obtain all fields and their values ​​in the specified Key .

 

```
7. LIST
```
Example:
> LPUSH tasks "Task 3"
1
> LPUSH tasks "Task 2"
2
> LPUSH tasks "Task 1"
3
> LRANGE tasks 0 -1
1) "Task 1"
2) "Task 2"
3) "Task 3"
> LPOP tasks
"Task 1"

 

illustrate:
The LIST command is used to insert, obtain, and delete values ​​in the list of specified Keys .
```
8. SET
```
Example:
> SADD colors "red" "green" "blue"
3
> SMEMBERS colors
1) "green"
2) "red"
3) "blue"

 

illustrate:
The SET command is used to add elements to the set of the specified Key , and the SMEMBERS command is used to obtain all elements in the set of the specified Key .
```

REDIS persistence


Overview

Redis provides two methods for persistence, RDB and AOF .
RDB : Regularly dumps Redis data in memory to a snapshot file on the hard disk for backup and recovery. Its advantages are safety, reliability and high performance. Its disadvantage is that the risk of data loss after the latest RDB file is dumped is high.
AOF : Record all write operations to Redis in an append-type file for data recovery. The advantage is that the risk of data loss is lower, but the disadvantage is that compared to RDB files, the file size is larger and the recovery speed is slower.
The persistence method can be controlled through the following parameters in the configuration file:
- save : set within N seconds, if M keys are modified, an RDB operation will be automatically performed; - appendfsync : set the method of data synchronization, such as always means synchronization for every operation, everysec means synchronization every second Once, no means not synchronized
It should be noted that when RDB and AOF persistence modes are enabled at the same time, AOF has a higher priority than RDB when restoring data .
To configure RDB persistence in Redis , you need to set it in the redis.conf configuration file

RDB persistence configuration

```
#After how long, if how many keys change, Redis performs a write operation
save 900 1
save 300 10
save 60 10000
#The name and location of the persistent file
dbfilename dump.rdb
#Directory to save persistent files
dir /var/lib/redis
```
In the above example, three save statements are configured, which means that if at least 1 key-value pair is modified within 900 seconds, Redis will automatically perform an RDB persistence operation to write the data snapshot in memory to in the disk. The other two parameters represent further persistence cycle settings. dbfilename represents the name of the persistent file, and dir represents the directory in which the persistent file should be saved.
In addition to manual settings in the configuration file, Redis can be configured in real time using the CONFIG SET command . Use the command SET CONFIG AUTO-AOF-SYNC YES to turn on automatic AOF synchronization, and use the SAVE command to immediately force an RDB persistence operation.
Redis 's AOF persistence refers to recording every write operation performed by the Redis server in an appended log file. This ensures that even if the server fails, the latest data will not be lost. Redis 's AOF persistence has the following two methods:
1. always : Synchronization will be performed every time a write operation occurs, which will affect the write performance of the server, but the degree of data protection is high.
2. everysec : performs a synchronization operation every second, a compromise option that ensures both writing performance and data security.

AOF persistence

1. Turn on the AOF persistence function by editing the configuration file redis.conf :
```
appendonly yes
```
2. Set the name of the AOF log file:
```
# AOF file name, the default value is appendonly.aof appendfilename "myappendonly.aof"
```
3. Set the storage directory of AOF logs:
```
# AOF storage path, the default value is "./"
dir /path/to/appendonly/
```
4. Set the synchronization frequency of AOF persistence:
```
#Set the data synchronization method, always means synchronization for every operation, everysec means synchronization once per second
appendfsync everysec
```
5. Restart the Redis service to take effect:
```
sudo systemctl restart redis
```
After completing the above steps, Redis can use AOF persistence. It should be noted that AOF persistence will bring certain performance losses, so try to choose a synchronization strategy once every second to ensure a balance between data security and performance.

REDIS data recovery


Redis provides a variety of data recovery methods: recovering from RDB persistent files, recovering from AOF persistent files, and using the Redis replication function to recover data from the main database.
Following are the steps to recover data using RDB and AOF persistent files:
1. Use the commands that come with Redis to restore data. If you are using RDB persistence, you can find the latest dump.rdb file and execute the command under redis-cli :
```
redis-cli --raw < /var/lib/redis/dump.rdb
```
If you are using AOF persistence, you can use the bgrewriteaof command or filter operation to obtain the recovery file:
```
#Use bgrewriteaof command _
redis-cli bgrewriteaof
grep -i "set.*key_name" /var/lib/redis/appendonly.aof > /var/lib/redis/redis_restore.aof
#Or use sed to filter
sed -n '/^.*set.*key_name.*$/p' /var/lib/redis/appendonly.aof > /var/lib/redis/redis_restore.aof
#restore _
redis-cli --pipe < /var/lib/redis/redis_restore.aof
```
2. Copy the recovery file to the directory where the new Redis server is located.
3. Start the Redis server.
4. Make sure persistence is enabled in the redis.conf file . If it is enabled, execute the following command:
```
redis-server /path/to/redis.conf
```
After executing the above command, the recovered data can be used. These two methods can be flexibly selected according to actual needs.
It should be noted that the data in the Redis persistence file may not be the latest, so the timeliness and completeness of data recovery need to be confirmed before data recovery. If too much data is lost, it is best to try to use the Redis replication function to recover the data in addition to backup and recovery.

REDIS sample data


The official Redis website provides some sample data that can be used to learn and test the functions of Redis . You can go to the download page of the Redis official website to get the sample data file. 
The specific download steps are as follows:
1. Open the download page of Redis official website (https://redis.io/download)
 
2. Find the "Sample datasets for Redis" section on the page
3. Click the link and select a sample data file you want to download.
The sample data files currently provided include the following:
- big_data.zip : Redis data set containing some extremely large data .
- country_zip_fat_j.txt : Country table, which can be used to test functions such as fuzzy search and sorting.
- gfiber.py : Python script for generating a binary Google Fiber dataset .
- geo_data.py : used to generate a Python script containing random geographical location data .
- hello-world.txt : A simple Redis tutorial data set.
You can choose to download according to your needs. After the download is complete, unzip the sample data file, and then use the Redis client to import the data into the Redis database to start using and learning the Redis database functions.

REDIS import data


Redis supports multiple ways to import data. Common ways include :
1. Import data through Redis’ own commands
You can use the data import command `SET` that comes with Redis and the corresponding data type command to add data to the Redis database. For example:
```
SET key1 value1
HASHSET key2 field1 value1 field2 value2
LIST key3 value1 value2 value3
SET key4 value1 value2 value3
```
2. Import data through Redis client tool
The Redis client tool `redis-cli` can use `SET` , `MSET` , `HSET` , `HMSET` and other commands. It can also save data in a text file and then import it into the database. For example:
To import the data saved in the file `data.txt` into the Redis database, you can use the following command:
```
cat data.txt | redis-cli --pipe
```
3. Import data through the persistence function of Redis
Data that has been persisted can be imported into the Redis database through the following command:
```
redis-cli --raw < dump.rdb
```
Note: Using this command will overwrite all data in the Redis database.
4. Import data through Redis data backup / restore
Using the Redis data backup / restore tool, when restoring the backup file to a new Redis instance, the data in the backup file will be imported into the Redis database.
Assuming that you already have a Redis data backup `dump.rdb` , you can use the following command to restore the data:
```
redis-server --appendonly yes
redis-cli --rdb ./dump.rdb
```
The above are common ways for Redis to import data. You can choose a method to import data into the Redis database according to your specific situation .

Guess you like

Origin blog.csdn.net/2302_77750172/article/details/131169322