Summary of Redis commonly used commands and data types

* Common Redis commands:
log in to redis-cli to
search for a keyword KSYS 4
check whether the key exists EXISTS key
return the type of vsl affected by a key TYPE key

1. Download and install:

1. Go to the redis official website to
download the latest version of redis

[[email protected] redis]# mkdir /usr/local/redis
[[email protected] redis]# rz -y 

2. Install the compilation environment

[[email protected] redis]# yum install gcc -y
[[email protected] redis]# tar -zvxf redis-6.2.3.tar.gz -C /usr/local/redis
  cd redis-6.2.3/
  [[email protected] redis-6.2.3]# make  #编译
  [[email protected] redis-6.2.3]# make install  #编译安装

  安装目录 :/usr/local/bin

3. Start

  前台启动 (不推荐)
  [[email protected] bin]# redis-server 


  后台启动 (推荐)

3.1. Copy a copy of redis.conf to other directories

  [[email protected] redis-6.2.3]# pwd
[[email protected] redis-6.2.3]# cp redis.conf /etc/redis.conf #复制redis.conf 到/etc/中

3.2. Change daemonizs no to yes in background startup setting

[[email protected] etc]# cd /usr/local/bin/
[[email protected] bin]# redis-server /etc/redis.conf  #启动,后面路径为刚拷贝文件的路径
[[email protected] bin]# ps -ef | grep redis #查看是否启动成功
root       13447       1  0 22:57 ?        00:00:00 redis-server
root       13488    2092  0 22:57 pts/0    00:00:00 grep --color=auto redis

[[email protected] bin]# #Also
connect to redis through the client

4. Redis is off

Single instance shutdown: redis-cli shutdown
finds the process number and kills:

[[email protected] bin]# ps -ef | grep redis
root       14463       1  0 23:04 ?        00:00:00 redis-server
root       14477    2092  0 23:04 pts/0    00:00:00 grep --color=auto redis
[[email protected] bin]# kill -9 14463

2. Redis key (key)

keys * 查看当前所有key (匹配:keys *1)
exists key [key ...]:查询一个key是否存在,时间复杂度为O(1),存在返回1,否则返回0

del key [key ...]:删除指定的key(一个或多个),时间复杂度O(N),N为要删除的key的个数

dump key:序列化给定key,并返回被序列化的值,使用RESTORE命令可以把这个值反序列化为Redis的键。

RESTORE key ttl serialized-value [REPLACE]:反序列化给定的序列化值,并将它和给定的key关联。
type key 查看你的key 是什么类型

unlink key 根据value 选择非阻塞删除
仅将keys从keyapace 元数据中删除,真正的删除会在后续异步操作
exoire key 10   10秒钟:为给定的key 设置过期时间

ttl key 查看还有多少秒过期,-1 表示永不过期,-2表示已过期

select 命令切换数据库
dbsizs 查看当前数据库的key的数量
flushdb 清空当前库
flushall 通杀全部库

Three, commonly used commands

 set <key> <value> 添加键值对
 NX:当数据中key 不存在时,可以将key-value 添加数据库
 XX:当数据中key 存在时,可以将key-value 添加数据库,与NX参数互斥
 PX:key 的超时毫秒数,与EX互斥

 get <key> 查询对应键值
 append <key> <value> 将给定的<value> 追加到原值的末尾
 strlen <key> 获得值的长度
 setnx <key><value> 只有在key不存在时,设置key的值

 incr <key>
      将key 中储存的数字增值 1

 decr <key>     
Redis 字符串 (string)

Fourth, the list of commonly used data

4.1 Redis List List

The single-key multi-value
Redis list is a simple list of strings, sorted according to the insertion order, you can add an element to the head (left) or the tail (right).
Its bottom layer is actually a doubly linked list, which has high performance on both ends. The performance of the nodes in the middle of the operation through the index subscript will be poor.

Common commands:
① lpush/rpush… insert one or more values ​​from the left/right side
Test: put data to the left> LPUSH k1 v1 v2 v3
(integer) 3> lrange k1 0 -1
1) "v3"
2) "v2"
3) "v1"

Test: put data to the right> rpush k2 v1 v2 v3
(integer) 3> lrange k2 0 -1
1) "v1"
2) "v2"
3) "v3"

② lpop/rpop spit out a value from the left/right. The value is in the key, and the value is in the key.> lpop k1
"v3"> rpop k2

③ rpoplpush spit out a value from the right side of the list and insert it to the left side of the list> lpush k1 v1 v2 v3
(integer) 3> rpush k2 v11 v12 v13
(integer) 3> keys *
1) "k2"
2) "k1"> rpoplpush k1 k2

④ lrange  
Get the elements according to the index subscript (from left to right)
lrange mykist 0 -1 is the first on the left, -1 is the first on the right, (0-1 means get all) ```bash> lrange k2 0 -1
1) "v1"
2) "v11"
3) "v12"
4) "v13"

⑤ lindex gets the elements according to the index subscript (from left to right)> lindex k2 0
"v1"> lindex k2 2

⑥lleb get the length of the list> llen k2 

⑦ Insert value after linsert before> linsert k2 before "v11" "newv11"
(integer)5> lrange k2 0 -1
1) "v1"
2) "newv11"
3) "v11"
4) "v12"
5) "v13"> linsert k2 before "v13" "newv11"
(integer)6> lrange k2 0 -1
1) "v1"
2) "newv11"
3) "v11"
4) "v12"
5) "newv11"
6) "v13"

⑧ lrem deletes n values ​​from the left (from left to right)> lrem k2 2 "newv11"
(integer) 2> lrange k2 0 -1
1) "v1"
2) "v11"
3) "v12"
4) "newv11"
5) "v13"

⑨ lset replaces the value of the list key subscript as index with value> lest k2 1 abc
ok> lrange k2 0 -1
1) "v1"
2) "abc"
3) "v12"
4) "newv11"
5) "v13"

4.2 Redis set (Set)

The external function provided by redis set is similar to the function of a list. The special feature is that the set can automatically sort the weight. When you need to store a list of data and do not want duplicate data, set is a good choice , And set provides an important interface for judging whether a member is in a set collection, which is also not provided by list

Redis set is an unordered collection of string type. Its bottom layer is actually a bash table whose value is null, so the complexity of adding, deleting, and searching is 0 (1)

An algorithm, as the data increases, the length of the execution time, if it is 0 (1), the data increases, and the time to find the data does not change

1.sadd …
Add one or more member elements to the set key, the existing member elements will be ignored> sadd k1 v1 v2 v3
(integer) 3

2.smembers take out all the values ​​of the set> smembers k1
1) "v1"
2) "v2"
3) "v3"

3. sismember judges whether the set contains a value, it returns 1 but does not return 0> sismember k1 v1
(integer) 1> sismember k1 v11
(integer) 0

4.scard: returns the number of collection elements> scard k1
(integer) 3

5.srem: delete the specified element in the combination> srem k1 v1 v2
(integer) 2> smembers k1
1) "v3"

6.spop randomly spit out a value from the set> spop k2

7. srandmember randomly takes out n values ​​from the set and will not delete it from the set> srandmember k2 2
1) "v1"
2) "v2"

8.smovevalue moves a value in the collection from one collection to another collection> sadd k1 v1 v2 v3
(integer) 3> sadd k2 v3 v4 v5
(integer) 3> smove k1 k2 v3
(integer) 1> smembers k1
1) "v1"
2) "v2"> smembers k2
1) "v4"
2) "v5"
3) "v3"

9.sinter returns the intersection element of two sets> sinter k2 k3
1) "v4"

10.sunion returns the union element of two sets> sunion k2 k3
1) "v4"
2) "v3"
3) "v5"
4) "v7"
5) "v6"

11.sdiff returns the difference set elements of the two sets (key1, excluding key2)> sdiff k2 k3
1) "v3"
2) "v5"

4.3 Redis Hash (Hash)

Redis hash is a collection of key-value pairs.
Redis hash is a mapping table of string field and value. Hash is especially suitable for storing objects. Similar to Map<String,Object> in Java, the
user ID is the key to be looked up, and the stored value user object contains information such as name, age, birthday, etc. If you use a common key/Value structure to store

Common commands

  1. Key assignment in the hset collection> hset user:1001 id 1
(integer) 1> hset user:1001 name zhangsan
(integer) 1
  1. hget retrieves value from the collection> hget user:1001 id
"1"> hget user:1001 name
  1. hmset… set hash values ​​in batches> hmset user:1002 id 2 name lisi age 36
  1. hexists check whether the given field exists in the hash table key> hexists user:1002 id
(integer) 1> hexists user:1002 name
(integer) 1> hexists user:1002 gende
(integer) 0
  1. hkeys lists all fields in the hash set> hkeys user:1002
1) "id"
2) "name"
3) "age"
  1. hvals lists all the values ​​of the hash set> hvals user:1002
1) "2"
2) "lisi"
3) "36"> 
  1. hincrby is the value of the field field in the hash table key plus an increment of 1 -1> hincrby user:1002 age 2
(integer) 38
  1. hsetnx sets the value in the hash table key to value, and only if the field does not exist> hsetnx user:1002 age 40
(integer) 0> hsetnx user:1002 gende 1
(integer) 1> hkeys user:1002
1) "id"
2) "name"
3) "age"
4) "gende"

The data structure of the
hash type corresponds to two data structures: ziplist (compressed list), hashtable (hash table), when the field-value length is short and the number is small, use ziplist, otherwise use hashtable

4.4 Redis ordered set Zset (sorted set)

Redis ordered collection zset is very similar to ordinary collection set, it is a collection of strings without repeated elements. The difference is that each member of the ordered set is associated with a score, which is used to sort the members in the set from the lowest score to the highest score. The members of the set are unique, but the scores can be repeated

Because the elements are ordered, you can quickly get a range of elements based on the score or position.

Access to the middle elements of an ordered set is also very fast, so you can use an ordered set as a smart list with no duplicate members.

Common commands

  1. zadd …
    Add one or more member elements and their score values ​​to the ordered set of keys.> zadd  topn 200 java 300 c++ 400 mysql 500 php
(integer) 4
  1. zrange     [WITHSCORES] returns the ordered set key, the subscript is     Elements between:> zrange topn 0 -1
1) "java"
2) "c++"
3) "mysql"
4) "php"

3. With WITHSCORES, the score and value can be returned to the result set together.> zrange topn 0 -1 withscores
1) "java"
2) "200"
3) "c++"
4) "300"
5) "mysql"
6) "400"
7) "php"
8) "500"
  1. zrangebyscore key minmax [withscores [limit offset count]
    returns an ordered set of keys with all score values ​​between min and max including members equal to min or max. The members of the ordered set are arranged in the order of increasing score value (from small to large).> zrangebyscore topn 300 500 withscores
1) "c++"
2) "300"
3) "mysql"
4) "400"
5) "php"
6) "500"
  1. zrevrangebyscore key maxmin [withscores] [limit offset count is the
    same as above, but sorted from largest to smallest.> zrevrangebyscore topn 500 200
1) "php"
2) "mysql"
3) "c++"
4) "java"> zrevrangebyscore topn 500 200 withscores
1) "php"
2) "500"
3) "mysql"
4) "400"
5) "c++"
6) "300"
7) "java"
8) "200"
  1. zincrby adds an increment to the score of the element> zincrby topn 50 java
  1. zrem deletes the element of the specified value in the set> zrem topn php 
  1. zcount counts the number of elements in the set, the score interval> zcount topn 200 300
  1. zrank returns the ranking of the value in the collection, starting from 0
    Case: How to use zset to achieve a ranking of article visits?> zrank topn java
(integer) 1> zrange topn 0 -1
1) "javca"
2) "java"
3) "c++"
4) "mysql"
5) "php"> zrange topn 0 -1 withscores
 1) "javca"
 2) "50"
 3) "java"
 4) "250"
 5) "c++"
 6) "300"
 7) "mysql"
 8) "400"
 9) "php"
10) "500"

data structure

SortedSet (zset) is a very special data structure provided by Redis. On the one hand, it is equivalent to the Java data structure Map<String, Double). It can assign a weight to each element value. On the other hand, it is similar to TreeSet, the internal elements will be sorted according to the weight score, you can get the ranking of each element, and you can also get the list of elements through the range of score.
The bottom layer of zset uses two data structures.
(1) Hash, the function of hash is to associate element value and weight score to ensure the uniqueness of element value, and the corresponding score value can be found through element value.
(2) Jump table. The purpose of the jump table is to sort the value of the elements and obtain the element list according to the range of the score.

Jump table (jump table)
2.1 Introduction
Ordered collections are more common in life, such as ranking students based on their scores and ranking players based on their scores
. For the underlying implementation of ordered collections, arrays, balanced trees, linked lists, etc. can be used. Insertion and deletion of inconvenient elements in the array: Although the balanced tree or the red-black tree has high efficiency, the structure is complicated; the linked list query needs to traverse all the efficiency. Redis uses a jump table. The efficiency of the jump table is comparable to that of the red-black tree, and the implementation is far simpler than that of the red-black tree.
2.2 Example
Compare the ordered linked list and the jump list, and query 51
(1) ordered linked list from the linked list

Insert picture description here

To find an element with a value of 51, you need to search and compare the dishes in order from the first element. A total of 6 comparisons are required.

(2) Jump table

Insert picture description here

Starting from the second layer, 1 node is smaller than 51 nodes, and
21 nodes are smaller than 51 nodes in the backward comparison. Continue to compare backward, and the next is NULL, so from 21 nodes down to the first layer
in the first layer, 41 nodes It is smaller than the 51 node, and continues to the back. The 61 node is larger than the 51 node, so from 41 to the bottom.
At the 0th level, the 51 node is the node to be searched. The node is found, a total of 4 searches

From this we can see that skip lists are more efficient than ordered linked lists.