Data types in Redis and their basic usage

1. Redis string

Redis string data type related commands are used to manage string values.

1. View all keys;

keys *

2. Set up a key-value pair;

set name zhangsan

3. Set a key-value pair and add the expiration time, the time unit is seconds;

set name zhangsan EX 30

4. Obtain data to data;

get name

5. Delete the specified key value;

del name

6. Delete all data;


7. View the type;

type name

8. Set the expiration time of a key;

expire name 20

2. Redis list

The Redis list is a simple list of strings, sorted in the order of insertion, and data can be inserted or deleted from the left or from the right.

Although Redis lists are very similar to arrays, they are implemented using linked lists.

1. Increase the value on the right side of the list;

rpush userList zhangsan

2. Increase the value on the left side of the list;

lpush userList zhangsan

3. Delete the value on the right;

rpop zhangsan

4. Delete the value on the left;

lpop zhangsan

5. Get list data;

lrange userList 0 -1

6. Delete data;

del userList

7. Delete all data;


8. View the type;

type userList

3. Redis Collection

The Redis collection is an unordered collection of string types, and the members in the collection are unique, which means that no duplicate data can appear in the collection.

In Redis, collections are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1).

1. Add data to the collection;

sadd userList zhangsan

2. Delete a value in the set;

srem userList zhangsan

3. Obtain collection data;

smembers userList

4. Delete data;

del userList

5. Delete all data;


4. Redis hash

Redis hash is a mapping table of string type fields and values, which is especially suitable for storing objects.

1. Set a single value;

hset zhangsan name "张三"

2. Set multiple values;

hmset zhangsan name "张三" age 20 sex “男”

3. Get data;

hgetall zhangsan

4. Delete data;

del zhangsan

5. Delete all data;


5. Redis subscription release

Redis publish and subscribe is a message communication mode: the sender sends a message, and the subscriber receives the message.

Redis clients can subscribe to any number of channels.

The following figure shows the channel channel1 and the relationship between the three clients client1, client2, and client5 that subscribe to this channel:

When a new message is sent to channel channel1 through the PUBLISH command, the message will be sent to the three clients that subscribe to it: