Redis high performance database

1, Redis overview:

Redis: it is a persistent single process and single thread key value type cache system. Similar to memcached, it supports relatively more stored value types, including string (string), list (list), set (set) zset(sorted set -- ordered set) and hashes (hash type). These data types all support push/pop, add/remove, intersection, union, difference and richer operations. Like memcached, data is cached in memory to ensure efficiency. The difference is that redis will periodically flush database data to the hard disk through asynchronous operations for saving. Because it is a pure memory operation, redis has excellent performance every second It can handle more than 100000 read and write operations. It is the fastest known key value dB and realizes master-slave synchronization on this basis. At present, redis is widely used. Redis cache services are used in China, such as Sina and Taobao, and abroad, such as Flickr and Github. Official website address: https://redis.io/ At present, the development and maintenance of redis project is supported by vmware manufacturers

advantage:

1. Extremely high performance. Redis can support read and write frequencies of more than 100K + per second
2. Rich data types: Redis supports string, lists, hashes, sets and Ordered Sets data type operations for binary cases

3. Atomicity} all Redis operations are atomicity (that is, all operations either succeed or fail to be executed). At the same time, Redis also supports atomicity execution after full consolidation of several operations
4. Redis runs in memory but can be persisted to disk. Therefore, it is necessary to weigh the memory when reading and writing different data sets at high speed, because the amount of data cannot be greater than the hardware memory. Another advantage of in memory database is that compared with the same complex data structure on disk, it is very simple to operate in memory, so redis can do many things with strong internal complexity. At the same time, in terms of disk format, they are compact and generated in an additional way, because they do not need random access

2, Application scenario analysis:

Problems with MySql+Memcached architecture: in fact, MySQL is suitable for massive data storage. Hot data is loaded into the cache through Memcached to speed up access. Many companies have used this architecture, but with the continuous increase of business data and access, they will encounter many problems:
1. MySQL needs to continuously disassemble databases and tables, and Memcached also needs to continuously expand its capacity. Capacity expansion and maintenance occupy a lot of development time
2. Data consistency between Memcached and MySQL databases
3. The hit rate of Memcached data is low or down, and a large number of accesses directly penetrate into the DB, which cannot be supported by MySQL
4. cache synchronization across machine rooms

Redis application scenario:

Redis is more like an enhanced version of Memcached, so when to use Memcached and redis?

1. Redis not only supports simple k/v data, but also provides storage of list, set, zset, hash and other data structures
2. Redis supports data backup, that is, data backup in master slave mode
3. Redis supports data persistence. It can keep the data in memory on disk and can be loaded again for use when restarting
4. Memcached: reduce database load and improve performance in dynamic system; Caching is suitable for more reading and less writing and large amount of data (such as Renren's massive query of user information, friend information, article information, etc.)
Redis: it is applicable to systems with high requirements for reading and writing efficiency, complex data processing business and high requirements for security (such as the counting and publishing systems of sina Weibo, which have high requirements for data security and reading and writing)

3, Redis's data recycling strategy:

Redis recycling policy
volatile-lruSelect the least recently used data from the data set with expiration time (server.db[i].expires)
volatile-ttlSelect the data set (server.db[i].expires) whose expiration time has been set to expire
volatile-randomSelect any data from the dataset (server.db[i].expires) for which the expiration time has been set
allkeys-lruSelect the least recently used data from the data set (server.db[i].dict)
allkeys-randomSelect any data from the dataset (server.db[i].dict)
No evictionProhibition of expulsion data

4, Deploy Redis high performance database

IP addresshost namesystemSoftware
192.168.2.7C7--07CentOS 7.4

redis-6.2.6.tar.gz

Download address: Redis Download

 1. Install Redis

Redis-6.2 is used here Version 6

[root@C7--07 ~]# tar zxvf redis-6.2.6.tar.gz                                      
[root@C7--07 ~]# cd redis-6.2.6                                 
[root@C7--07 redis-6.2.6]# make                             
[root@C7--07 redis-6.2.6]# echo $?                         
[root@C7--07 redis-6.2.6]# cd                               
[root@C7--07 ~]# mkdir -p /usr/local/redis                                 
[root@C7--07 ~]# cp /root/redis-6.2.6/src/redis-server /usr/local/redis/        #Server program
[root@C7--07 ~]# cp /root/redis-6.2.6/src/redis-cli /usr/local/redis/           #Client program
[root@C7--07 ~]# cp /root/redis-6.2.6/redis.conf /usr/local/redis/              #Master profile
[root@C7--07 ~]# ls /usr/local/redis/
redis-cli  redis.conf  redis-server

[root@C7--07 ~]# sed -i '/^bind/s/bind .*/bind 192.168.2.7/g' /usr/local/redis/redis.conf   #Change to local address
[root@C7--07 ~]# sed -i '/protected-mode/s/yes/no/g' /usr/local/redis/redis.conf            #Turn off the protection mode of redis
[root@C7--07 ~]# sed -i '/daemonize/s/no/yes/g' /usr/local/redis/redis.conf                 #Enable the background daemon mode of redis
[root@C7--07 ~]# sed -i '/requirepass/s/foobared/123.com/g' /usr/local/redis/redis.conf     #Set the password of redis to 123 com
[root@C7--07 ~]# sed -i '/requirepass 123.com/s/^#//g' /usr/local/redis/redis.conf # enable redis password

2. Detailed description of main configuration file

 -----@@@@@@@@-----            redis.conf Main profile details   ----No change---

daemonize yes                                   #Running redis in daemon mode
pidfile "/var/run/redis.pid"                    #Redis runs in the background. The default PID file path is / var / run / redis pid
port 6379                                       #Default port
bind 127.0.0.1                                  #All ip addresses of the machine are bound by default. For security, you can only listen to intranet ip addresses
timeout 300                                     #Client timeout setting, in seconds
loglevel verbose                                #Set the log level and support four levels: debug, notice, verbose and warning  
logfile stdout                                  #The log recording mode is standard output by default. logs does not write files and is output to an empty device / deb/null
logfile "/usr/local/redis/var/redis.log"        #You can specify the log file path
databases 16                                    #Number of open databases

save 900 1
save 300 10
save 60 10000
 Create local database snapshot, format: save * *
900 Within seconds, the snapshot is triggered after performing one write operation
300 Within seconds, perform 10 write operations
60 10000 writes per second

rdbcompression yes                             #Enable database lzf compression or set to no
dbfilename dump.rdb                            #Local snapshot database name
dir "/usr/local/redis/var/"                    #Local snapshot database storage directory
requirepass 123.com                            #Set redis database connection password
maxclients 10000                               #The maximum number of client connections at the same time. 0 is unlimited
maxmemory 1024MB                               #Set the maximum memory used by redis. The value must be smaller than the physical memory
appendonly yes                                 #Enable logging, which is equivalent to MySQL binlog
appendfilename "appendonly.aof"                #Log file name. Note: it is not a directory path
appendfsync everysec                           #Set the frequency of log synchronization and perform synchronization every second. The two parameters always and no are generally set to everysec, which is equivalent to the writing mode of MySQL transaction log
Slaveof                                        #Set the database as the slave database of another database
Masterauth                                     #Password authentication required for primary database connection
vm-enabled                                     #Whether to enable virtual memory support (the parameters at the beginning of vm are used to configure virtual memory)
vm-swap-file                                   #Sets the swap file path for virtual memory
vm-max-memory                                  #Set the maximum physical memory size used by redis
vm-page-size                                   #Sets the page size of virtual memory
vm-pages                                       #Set the total number of page s of the swap file
vm-max-threads                                 #Set the number of threads used simultaneously for swap storage. Usually, the value is the same as the number of cores. If it is set to 0, it will be in serial mode, which greatly ensures the integrity of data
Glueoutputbuf                                  #Store small output caches together
hash-max-zipmap-entries                        #Set the critical value of hash
Activerehashing                                #Re hash

3. Write a script to start and stop redis

 ######          Write start stop redis script   

------------Direct copy and paste note:If you change the password, you need to change the password here AUTH="123.com"

[root@C7--07 ~]# cat <<END >>/etc/init.d/redis
#!/bin/sh
# chkconfig: 2345 80 90
# description: Start and Stop redis
#PATH=/usr/local/bin:/sbin:/usr/bin:/bin
REDISPORT=6379
EXEC=/usr/local/redis/redis-server
REDIS_CLI=/usr/local/redis/redis-cli
PIDFILE=/var/run/redis_6379.pid
CONF="/usr/local/redis/redis.conf"
AUTH="123.com"
LISTEN_IP=$(netstat -utpln |grep redis-server |awk '{print $4}'|awk -F':' '{print $1}')
case "$1" in
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                $EXEC $CONF
        fi
        if [ "$?"="0" ]
        then
              echo "Redis is running..."
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."
                $REDIS_CLI -h $LISTEN_IP -p $REDISPORT -a $AUTH SHUTDOWN &>>/dev/null
                while [ -x ${PIDFILE} ]
               do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
   restart|force-reload)
        ${0} stop
        ${0} start
        ;;
  *)
    echo "Usage: /etc/init.d/redis {start|stop|restart|force-reload}" >&2
        exit 1
esac
END

4. Startup

[root@C7--07 ~]# chmod 755 /etc/init.d/redis                                 
[root@C7--07 ~]# chkconfig --add redis                             
[root@C7--07 ~]# /etc/init.d/redis start                              
Starting Redis server...
Redis is running...

[root@C7--07 ~]# netstat -autpln |grep redis                           
tcp        0      0 192.168.2.7:6379        0.0.0.0:*       LISTEN      89272/redis-server  

5. Adjust Redis service

[root@C7--07 ~]# cp /root/redis-6.2.6/src/{redis-benchmark,redis-check-rdb,redis-check-aof,redis-sentinel} /usr/local/redis/                                               
[root@C7--07 ~]# [root@C7--07 ~]# ls /usr/local/redis/                                             
redis-benchmark  redis-check-rdb  redis.conf  redis-server  redis-check-aof  redis-cli        redis-sentinel

[root@C7--07 ~]# ln -s /usr/local/redis/redis-cli /usr/bin/redis                                
[root@C7--07 ~]# redis -h 192.168.2.7 -p 6379 -a 123.com
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
192.168.2.7:6379> exit

Here, redis has been installed

6. Test Redis service with PHP

You need to connect to the Internet and add a network card: if you do not install the network yum source, an error may be reported later

[root@C7--07 ~]# yum -y install wget                
[root@C7--07 ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
................
100%[=====================================================>] 2,523       --.-K/s Time 0 s      

2021-12-16 20:45:20 (1.13 GB/s) - Saved“/etc/yum.repos.d/CentOS-Base.repo" [2523/2523])

[root@C7--07 ~]# yum -y install httpd php php-redis php-devel                      
[root@C7--07 ~]# php -v                                
PHP 5.4.16 (cli) (built: Apr  1 2020 04:07:17) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

Download PHP redis: https://codeload.github.com/phpredis/phpredis/tar.gz/4.0.2 You can download it directly

[root@C7--07 ~]# tar zxvf phpredis-4.0.2.tar.gz                 
............
.....
[root@C7--07 ~]# cd phpredis-4.0.2                 

[root@C7--07 phpredis-4.0.2]# /usr/bin/phpize                   
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525

[root@C7--07 phpredis-4.0.2]# ./configure --with-php-config=/usr/bin/php-config                     
.............
......
[root@C7--07 phpredis-4.0.2]# make && make install                                
...............
.....

[root@C7--07 phpredis-4.0.2]# echo $?             
0
[root@C7--07 phpredis-4.0.2]# cd
[root@C7--07 ~]# echo -e "extension_dir = \"/usr/lib64/php/modules/\"\nextension = redis.so" >>/etc/php.ini
[root@C7--07 ~]# systemctl start httpd
[root@C7--07 ~]# netstat -utpln |grep 80
tcp6       0      0 :::80                   :::*                    LISTEN      32054/httpd         

--------The following can be copied and pasted directly 

[root@C7--07 ~]# cat <<END >>/var/www/html/index.php          
<?php
phpinfo();
?>
END

-------Remember to modify IP And password

[root@C7--07 ~]# cat <<END >>/var/www/html/test.php
<?php
\$redis = new Redis();
\$redis->connect('192.168.2.7',6379);
\$redis->auth('123.com');
\$keys = \$redis->keys("*");
var_dump(\$keys);
?>
END

Access test: http://192.168.2.7/

visit: http://192.168.2.7/test.php

7. Redis related operations

String string of redis operations (Note: the statements in redis can be completed by tab)

Overview: string is a simple key value pair. Value can be not only a string, but also a number. String is stored in redis. By default, it is a string referenced by redisObject. When encountering operations such as incr and decr, it will be converted to numerical type for calculation. At this time, the encoding field of redisObject is int

[root@C7--07 ~]# redis -h 192.168.2.7 -p 6379 -a 123.com            

192.168.2.7:6379> set hello world                              
OK
192.168.2.7:6379> get hello                           
"world"              
192.168.2.7:6379> exists hello                 #Verify that the key exists
(integer) 1
192.168.2.7:6379> type hello           
string
192.168.2.7:6379> substr hello 1 2             #View the second and third characters of the key; By default, the first character is 0 and the second is 1
"or"
-----------------------------------
192.168.2.7:6379> append hello !!!!            #Add character after key!!!!
(integer) 9
192.168.2.7:6379> get hello            
"world!!!!"
-----------------------------------
192.168.2.7:6379> set qqq hhhhh~      
OK
192.168.2.7:6379> keys h*                      #View keys starting with h
1) "hehe"
2) "hello"
------------------------------------
192.168.2.7:6379> set ID 1453261
OK
192.168.2.7:6379> keys *
1) "hello"
2) "hehe"
3) "ID"
192.168.2.7:6379> randomkey                    #Random return of a Key
"ID"
------------------------------------
192.168.2.7:6379> rename hello name            #Modify the key name; Change hello to name
OK
192.168.2.7:6379> keys *
1) "name"
2) "hehe"
3) "ID"
-------------------------------------
192.168.2.7:6379> del hehe                    #Delete hehe
(integer) 1
192.168.2.7:6379> keys *
1) "name"
2) "ID"
-------------------------------------
192.168.2.7:6379> get ID
"1453261"
192.168.2.7:6379> set ID 444555                #Modify internal string
OK
192.168.2.7:6379> get ID
"444555"
-------------------------------------
192.168.2.7:6379> expire ID 50                 #Set the timeout for the KEY value
(integer) 1
192.168.2.7:6379> ttl ID                       #View the current remaining timeout of the KEY value
(integer) 44
192.168.2.7:6379> get ID
(nil)
192.168.2.7:6379> keys *
1) "name"

list of operations in Redis

Overview: redis list is a simple string list, which can be compared to std::list in C + +. In short, it is a linked list or a queue. You can add elements to the redis list from the head or tail. The maximum length of the list is 2 ^ 32 - 1, that is, each list supports more than 4 billion elements. Redis list is implemented as a two-way linked list, that is, it can support reverse lookup and traversal, which is more convenient for operation, but it brings some additional memory overhead. Many implementations within redis, including send buffer queue, also use this data structure

Application scenarios: Redis list has many application scenarios, and it is also one of the most important data structures in Redis. For example, twitter's attention list and fan list can be implemented by Redis's list structure. For example, some applications use Redis's list type to implement a simple lightweight message queue, producer push and consumer pop/bpop

[root@C7--07 ~]# redis -h 192.168.2.7 -a 123.com                
    
192.168.2.7:6379> rpush lia 1998            #Create a list and insert elements at the end
(integer) 1
192.168.2.7:6379> rpush lia 1999            #Verify element 0 to element 1 in the list
(integer) 2
192.168.2.7:6379> lrange lia 0 1           
1) "1998"
2) "1999"
----------------------------------------
192.168.2.7:6379> lpush lia 1555            #Insert an element at the head of the list
(integer) 3
192.168.2.7:6379> lrange lia 0 1
1) "1555"
2) "1998"
192.168.2.7:6379> lrange lia 0 2            #verification
1) "1555"
2) "1998"
3) "1999"
-----------------------------------------
192.168.2.7:6379> llen lia                  #View the number of elements in the list   
(integer) 3
-----------------------------------------
192.168.2.7:6379> lindex lia 1              #Navigate to the first element in the list
"1998"
-----------------------------------------
192.168.2.7:6379> ltrim lia 1 2             #Intercept the first element to the second element in the list
OK
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "1999"
-----------------------------------------
192.168.2.7:6379> lset lia 1 2021           #Change the value of the first element in the list to 2021
OK
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "2021"
-----------------------------------------
192.168.2.7:6379> lset lia 10 aaa         ---  #The element position when validating the change cannot be greater than the number of existing elements
(error) ERR index out of range
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "2021"
-----------------------------------------
192.168.2.7:6379> rpush lia 5000            #Insert a new element at the end of the list
(integer) 3
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "2021"
3) "5000"
-----------------------------------------
192.168.2.7:6379> rpush lia 5000
(integer) 4
192.168.2.7:6379> lrem lia 2 5000           #Delete two elements in the list with a value of 5000
(integer) 2
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "2021"
-----------------------------------------
192.168.2.7:6379> rpush lia 51
(integer) 3
192.168.2.7:6379> rpush lia 51
(integer) 4
192.168.2.7:6379> rpush lia 51
(integer) 5
192.168.2.7:6379> rpush lia 51
(integer) 6
192.168.2.7:6379> lrange lia 0 10
1) "1998"
2) "2021"
3) "51"
4) "51"
5) "51"
--------------------------------------
192.168.2.7:6379> lpop lia                   #Deletes the first element at the beginning of the list
"1998"
192.168.2.7:6379> lrange lia 0 10
1) "2021"
2) "51"
3) "51"
4) "51"

Set of operations in Redis -- unordered set

Overview: it can be understood as a pile of lists with non repeated values, which is similar to the concept of set in the field of mathematics. Redis also provides operations such as intersection, union and difference for sets. The internal implementation of set is a HashMap whose value is always null. In fact, it can quickly eliminate the duplication by calculating the hash, which is why set can judge whether a member is in the set

Application scenario: Redis set's external functions are similar to those of a list. The special feature is that set can automatically eliminate duplication. When you need to store a list data and do not want duplicate data, set is a good choice, and set provides an important interface to judge whether a member is in a set set, This is also not provided by the list. Or in the microblog application, if the people concerned by each user exist in a collection, it is easy to realize the function of seeking common friends between two people

192.168.2.7:6379> sadd qq 00                 #Create qq and assign 00
(integer) 1
192.168.2.7:6379> sadd qq 01                 #Create qq and assign 01
(integer) 1
192.168.2.7:6379> smembers qq                #Display all values of qq
1) "00"
2) "01"
-----------------------------------
192.168.2.7:6379> scard qq                   #How many elements does qq display
(integer) 2
-----------------------------------
192.168.2.7:6379> sismember qq 00            #Displays whether qq contains elements with a value of 00
(integer) 1
-----------------------------------
192.168.2.7:6379> srandmember qq             #Random return of element values in qq
"00"
-----------------------------------
192.168.2.7:6379> sadd qq2 00                #Create qq2 and add elements
(integer) 1
192.168.2.7:6379> sadd qq2 02
(integer) 1
-----------------------------------
192.168.2.7:6379> sinter qq qq2              #Filter the intersection of qq and qq2
1) "00"
-----------------------------------
192.168.2.7:6379> sinterstore qq3 qq qq2     #Save the intersection of qq and qq2 to qq3
(integer) 1
192.168.2.7:6379> smembers qq3
1) "00"
-----------------------------------
192.168.2.7:6379> sunion qq qq2              #Filter the union of qq and qq2
1) "00"
2) "02"
3) "01"
-----------------------------------
192.168.2.7:6379> sdiff qq qq2               #Relative to qq2, the difference set of qq1
1) "01"
192.168.2.7:6379> sdiff qq2 qq               #Relative to qq, the difference set of qq2
1) "02"
-----------------------------------    
192.168.2.7:6379> keys *                     #View keys for various data types that already exist
1) "qq2"
2) "name"
3) "qq"
4) "lia"
5) "qq3"

zset of operations in Redis -- ordered set

Overview: Redis ordered sets are similar to Redis unordered sets, except that a function is added, that is, the sets are ordered. Each member of an ordered set has a score for sorting. The time complexity of adding, deleting and testing Redis ordered collections is O (1) (fixed time, regardless of the number of element collections contained therein). The maximum length of the list is 2 ^ 32 - 1 elements (4294967295, more than 4 billion sets of each element)

Within Redis sorted set, HashMap and skip list are used to ensure the storage and order of data. The HashMap stores the mapping from member to score, while the skip table stores all members. The sorting is based on the score stored in HashMap. Using the structure of skip table can obtain high search efficiency and simple implementation

Usage scenario: the usage scenario of Redis sorted set is similar to that of set, except that set is not automatically ordered, while sorted set can sort members by providing an additional priority (score) parameter, and it is inserted orderly, that is, automatic sorting. When you need an ordered and non repetitive set list, you can choose the sorted set data structure

192.168.2.7:6379> zadd a1 1 abc          #Create the set a1, add the element abc, and set the score value of the element (the serial number of the ordered set) to 1
(integer) 1
192.168.2.7:6379> zadd a1 2 def
(integer) 1
192.168.2.7:6379> zadd a1 3 jqk
(integer) 1
192.168.2.7:6379> zrange a1 0 2          #View elements in collection a1
1) "abc"
2) "def"
3) "jqk"
----------------------------------
192.168.2.7:6379> zcard a1               #View cardinality in set a1
(integer) 3
----------------------------------
192.168.2.7:6379> zscore a1 jqk          #Verify the score value of the element jqk in the set a1
"3"
----------------------------------
192.168.2.7:6379> zrevrange a1 0 1       #Finds the elements in the collection in reverse order
1) "jqk"
2) "def"
----------------------------------
192.168.2.7:6379> zrem a1 jqk            #Delete the elements in the collection jqk
(integer) 1
192.168.2.7:6379> zrange a1 0 8          #Validate all elements in the collection
1) "abc"
2) "def"
-----------------------------------
192.168.2.7:6379> zincrby a1 8 @qq.com   #Set the score value of this element to 8 If this element does not exist, it is added to the collection
"8"
192.168.2.7:6379> zrange a1 0 8          #Verify the primary colors in the collection
1) "abc"
2) "def"
3) "@qq.com"
----------------------------------
192.168.2.7:6379> zrange a1 0 8 withscores  #View the value of the element in the collection and output its own score value
1) "abc"
2) "1"
3) "def"
4) "2"
5) "@qq.com"
6) "8"
----------------------------------
192.168.2.7:6379> zincrby a1 10 name        #Add a new element name and specify its own score value
"10"
192.168.2.7:6379> zrange a1 0 5 withscores  #Verify the ordering of elements
1) "abc"
2) "1"
3) "def"
4) "2"
5) "@qq.com"
6) "8"
7) "name"
8) "10"
----------------------------------
192.168.2.7:6379> zincrby a1 12 abc         #If the newly added element already exists, the specified score value will be added to the original score value
"13"
192.168.2.7:6379> zrange a1 0 5 withscores  #The score value of the validation element ABC changes to 13, increases by 12, and is sorted to the end of the set
 1) "def"
 2) "2"
 3) "@qq.com"
 4) "8"
 5) "name"
 6) "10"
 7) "abc"
 8) "13"

Note: in addition, there are zrevrank, zrevrange, zrangebycore, zremrangebyrank, zramrangebyscore, zinterstore / zunionstore and other operations

Operation hash in Redis

Overview: similar to dict type in c# or Hash in C + +_ Map type. The Value corresponding to Redis Hash is actually a HashMap. When there are few members in this Hash, Redis will use a compact storage method similar to one-dimensional array instead of the real HashMap structure in order to save memory. The encoding of the corresponding value redisObject is zipmap. When the number of members increases, it will be automatically converted to a real HashMap. At this time, the encoding is ht

Application scenario: suppose there are multiple users and corresponding user information, which can be used to store the user information with the user ID as the key, serialize the user information into, for example, json format and save it as value

192.168.2.7:6379> hset bbb kkk aaa           #Set the key value bbb, and specify the internal key corresponding to aaa
(integer) 1
---------------------------------------
192.168.2.7:6379> hget bbb kkk               #View the value of kkk in bbb
"aaa"
---------------------------------------
192.168.2.7:6379> hexists bbb kkk            #Check whether there is kkk in bbb
(integer) 1
---------------------------------------
192.168.2.7:6379> hset bbb kkk2 aaa2         #Create K2 in bbb
(integer) 1
---------------------------------------
192.168.2.7:6379> hlen bbb                   #View the cardinality of key values in bbb
(integer) 2
---------------------------------------
192.168.2.7:6379> hkeys bbb                  #View the specific keys contained in the bbb
1) "kkk"
2) "kkk2"
---------------------------------------
192.168.2.7:6379> hvals bbb                  #View the values contained in the bbb
1) "aaa"
2) "aaa2"
---------------------------------------
192.168.2.7:6379> hmget bbb kkk kkk2         #By explicitly specifying kkk in bbb, you can see what the value is
1) "aaa"
2) "aaa2"
---------------------------------------
192.168.2.7:6379> hgetall bbb                 #View the correspondence of all keys and values contained in the bbb
1) "kkk"
2) "aaa"
3) "kkk2"
4) "aaa2"
---------------------------------------
192.168.2.7:6379> hset bbb kkk4 20             #Add a new key K4 with a value of integer 20
(integer) 1
---------------------------------------
192.168.2.7:6379> hincrby bbb kkk4 10          #Add 10 to K4 execution (integers only)
(integer) 30
---------------------------------------
192.168.2.7:6379> hmset bbb kkk7 aaa7 kkk8 aaa8 kkk9 aaa9         #Batch add key value pairs
OK
192.168.2.7:6379> hgetall bbb                  #Validate key value pairs added in batch
 1) "kkk"
 2) "aaa"
 3) "kkk2"
 4) "aaa2"
 5) "kkk4"
 6) "30"
 7) "kkk7"
 8) "aaa7"
 9) "kkk8"
10) "aaa8"
11) "kkk9"
12) "aaa9"

Other operations in Redis

[root@redis ~]# redis -h 192.168.100.101 -p 6379 -a 123123
192.168.2.7:6379> dbsize                      #View the number of all key s
(integer) 7
 --------------------------------------------------
192.168.2.7:6379> flushdb                     #Delete all key s in the currently selected database
OK
--------------------------------------------------
192.168.2.7:6379> flushall                    #Delete all key s in all databases
OK
--------------------------------------------------
192.168.2.7:6379> save                        #Save data synchronization to disk
OK 
--------------------------------------------------
192.168.2.7:6379> bgsave                      #Asynchronous save
Background saving started
--------------------------------------------------
192.168.2.7:6379> lastsave                    #Unix timestamp of the last successful save to disk
(integer) 1639839487
--------------------------------------------------
192.168.2.7:6379> info                        #Query server information
# Server
redis_version:6.2.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:4ec33053fe9bc922
redis_mode:standalone
os:Linux 3.10.0-693.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
................
.......
--------------------------------------------------
192.168.2.7:6379> slaveof 192.168.2.7 6379   #Change replication policy settings
OK

Keywords: Database Redis Cache

Added by trp on Tue, 21 Dec 2021 05:25:03 +0200