How to store data in Redis to ensure that the queried data is in order

Method 1: Redis ordered set (sorted set, zset)

Redis ordered collection is similar to ordinary collection. It
is also a collection of string type elements, and duplicate members are not allowed.

The difference
between a Redis ordered set and a normal set is that each element is associated with a double type score . Redis uses scores to sort the members of the collection from small to large .

The members of the ordered set are unique, but the score (score) can be repeated.

Examples:

Add three values ​​to the ordered set of Redis through the command ZADD and associate the score

redis 127.0.0.1:6379> ZADD runoobkey 1 redis
(integer) 1
redis 127.0.0.1:6379> ZADD runoobkey 2 mongodb
(integer) 1
redis 127.0.0.1:6379> ZADD runoobkey 3 mysql
(integer) 1
redis 127.0.0.1:6379> ZADD runoobkey 3 mysql
(integer) 0
redis 127.0.0.1:6379> ZADD runoobkey 4 mysql
(integer) 0
redis 127.0.0.1:6379> ZRANGE runoobkey 0 10 WITHSCORES

1) "redis"
2) "1"
3) "mongodb"
4) "2"
5) "mysql"
6) "4"

Method 2: Redis list (list)

Redis lists have the characteristics of ordinary lists, that is, the data is ordered and repeatable. However, the bottom layer of the Redis list is implemented by a doubly linked list, so it has the characteristics of pressing or popping elements from both ends

Examples:

Push data in order from the left

redis 127.0.0.1:6379> LPUSH runoobkey redis
(integer) 1
redis 127.0.0.1:6379> LPUSH runoobkey mongodb
(integer) 2
redis 127.0.0.1:6379> LPUSH runoobkey mysql
(integer) 3
redis 127.0.0.1:6379> LRANGE runoobkey 0 10

1) "mysql"
2) "mongodb"
3) "redis"

note

Because the expiration time cannot be set for each element in the collection, we need to take other measures to solve the problem of expiration and clearing of collection elements. For example: (1) Timing tasks can be set; (2) For ordered collection, score can be set to timestamp to represent its expiration time

Guess you like

Origin blog.csdn.net/sinat_34241861/article/details/113845472