# Redis

# Rediskey

Database related operations

Redis has a total of 16 databases, and the default is database 0

Redis String (String)

String is the most basic data type of redis,

The String type is binary safe, and the Redis string can contain any data, such as pictures. serialized object

The String type is the most basic data type of Redis, and a character value in Redis can be up to 512M

Common commands for strings

set key value add key-value pair

# 清空数据库

flushdb

# 查看数据库中的键

keys *

#添加新数据

set k1 100

set k2 200

set k3 300

get key

get k1

append key value

# 在键为text的值的后面添加world

append text world

setnx key value

incr key For integers, it will be incremented by 1

decr key will decrease by 1 for integers

Increment or decrement on k1

Set the increment or decrement step size

incrby key increment

decrby key increment

# 设置k1的值自增100

incrby k1 100

mset key1 value1 key2 value2 … Set multiple key-value pairs at the same time

mget key1 key2 … Get multiple key-value pairs at the same time

At the same time, set key-value pairs that do not exist in multiple databases. If one of the keys exists, all content will not be created successfully.

msetnx key1 value1 key2 value2 …

strlen key Get the length of the string

getrange key start end traversal output

getrange name 0 -1

Get the first character and the third character

getrange name 0 2

setrange key start position value overwrite old value with new value

setex key expiration time value set the value and set the expiration time at the same time, the unit is second

# 过期时间20秒 值为v1

setex k5 20 v1

getset key value

getset k1 33

string data structure

The data structure of String is a simple dynamic string (Simple Dynamic String), which can be modified. The internal implementation structure is similar to the list in python. Some space is allocated in advance, and the size of the space will be automatically expanded when the space is not enough. , the maximum length is 512M

Redis list (List)

Redis lists are simple lists of strings, sorted in insertion order, and you can add elements to the head or tail of the list

Its bottom is actually a doubly-linked list, which has high operational performance on both ends, and the performance of operating intermediate nodes through index subscripts is poor.

List common commands

lpush/rpush key value1 value2 value3 Insert one or more values from left/right

lpop/rpop key Pop up a value from the left/right, the value is in the key, the key is dead

rpoplpush key1 key2 pops a value from the right of the key1 list and inserts it to the left of the key2 list

lrange key start stop Obtain elements according to the index subscript (from left to right)

code demo

lindex key index Obtain elements according to the index subscript

llen key Get the length of the list

linsert key before value newvalue Insert newvalue in front of value

Insert 99 in front of 3

linsert k1 before 3 99

Insert 55 behind 99

`lrem key n value`

Delete the 3 left 2s in the k4 list

lpush k4 1 2 2 3 2 1 5 2

lrem k4 3 2

lrange k4 0 -1

lset key index value Replace the value of the list key subscripted as index with value

lpush k5 1 2 3 4 5

# 将索引为2的值替换成22

lset k5 2 22

# 将索引为3的值替换成44

lset k5 3 44

list data structure

The data structure of list is a fast linked list

First, a contiguous memory storage will be used when there are fewer list elements. This structure is a ziplist compressed list, and all elements are in a contiguous memory space.

When there are many elements, it will be changed to quicklist,

Quicklist is a data structure that links multiple ziplists in the form of a doubly linked list

Redis collection (Set)

It is an unordered and non-repeating sequence, and the members of the set are unique

The operation is similar to list

The bottom layer is a hash table whose value is null. The complexity of adding, deleting and searching is O(1)

Collection of common commands

sadd key value1 value2 … Add elements to the collection key, if the newly added element already exists in the collection, it will be ignored

# 向s1集合中添加元素

sadd s1 1 2 3 4 4 4

smembers key

# 查看s1中的集合

smembers s1

sismember key value Determine whether the value exists in the collection, return 1 if yes, return 0 if not

sadd s2 1 2 3 4 5

sismember s2 2 # 返回1

sismember s2 6 # 返回0

scard key returns the number of collections

scard s2

srem key value1 value2 … Delete some elements in the collection

sadd s3 1 2 3 4 5 6 7 8

srem s3 3 4 7 # 删除成功

srem s3 3 # 当删除的元素不存在时，返回0，不会报错

spop key [count] Randomly pop up an element, or multiple elements

spop s3 # 随机弹出一个元素

spop s3 2 # 随机弹出2个元素

srandmember key [count] Randomly take out n values from the set and will not delete them from the set. The default n is 1. When n is greater than the length of the set, all elements in the set will be returned

srandmember s3 # 随机取出一个值

srandmember s3 2 # 随机取出2个值

move source destination value moves a value from one set to another

sadd s4 1 2 3

sadd s5 6 7 8

# s4中的2移动到s5中

smove s4 s5 2

The sets in redis are the same as the sets in mathematics, and they also have the calculation method of intersection, union, and difference

sinter key1 key2 returns the intersection of two sets

sunion key1 key2 returns the union of two sets

sdiff key1 key2 returns the difference of two sets

example

collection data structure

The data structure dict dictionary of the collection, the dictionary is implemented using a hash table, and all value values point to the same external value

Redis hash (Hash)

Redis hash is a collection of key-value pairs, a mapping table of string type and field and value, and hash is suitable for storing objects

Common Commands for Hash

hset key field value Set the value of the field field in the hash table key to value .

hget key field Get all fields and values of the specified key in the hash table

hmset key field1 value1 field2 value2 simultaneously sets multiple field-value (domain-value) pairs into the hash table key.

hmget key field1 field2 get all the values of the given field

hexists key filed Check whether the specified field exists in the hash table key.

hkeys key Get all the fields in the hash table

hvals key Get all values in the hash table.

hsetnx key field value Only if the field field does not exist, set the value of the hash table field.

hlen key Get the number of fields in the hash table

hincrby key field increment adds increment to the integer value of the specified field in the hash table key

hincrbyfloat key field increment is the floating point value of the specified field in the hash table key plus increment increment.

hdel key field1 [field2] delete one or more hash table fields

hash data structure

There are two data structures corresponding to the Hash type, ziplist (compressed list), hashtable (hash table)

When the field-value length is short and the number is small, ziplist is used, otherwise hashtable is used

Redis ordered collection Zset

Ordered collections are very similar to ordinary collections. They are sequences without repeated elements. The difference is that each element of an ordered collection is associated with a score (score). This score is used to sort from the lowest score to the highest score. elements in an ordered set,

Note: The elements in the collection are not repeatable, but the scores can be repeated

Common Commands for Sorted Sets

zadd key key score1 value1 score2 value2 … Add one or more member elements and score values to the ordered set

zrange key start stop Return the elements in the ordered set key whose subscripts are between start and stop, add the parameter withscores, and return it to the result set together with the score and value

zrangebyscore key min max returns all the members whose score value is between min and max in the sorted set, including min and max. The returned results are in ascending order of score

zrevrangebyscore key min max returns all members whose score value is between min and max including min and max in the sorted set. The returned results are from large to small by score

zcard key Get the number of members of the ordered set

zcount key min max counts the number of members in a sorted set with the specified interval fraction

Zincrby key increment member In the ordered set, the score of the specified member is added to the incremental increment

zinterstore destination numkeys key [key …] Computes the intersection of the given sorted set or sets and stores the result set in a new sorted set destination

zlexcount key min max Calculate the number of members in the specified dictionary interval in the ordered set

zrank key member returns the index of the specified member in the sorted set

zrem key member [member …] Remove one or more members of the sorted set

zremrangebyscore key min max Remove all members of the given score range in the sorted set

zscore key member Returns the score value of the member in the sorted set