当前位置:网站首页>Redis data type usage scenario
Redis data type usage scenario
2022-04-23 05:06:00 【hi wei】
redis Data type of
redis It mainly supports five data types :string、list、hash、set、zset
redis There are a lot of orders , We can look at the documentation , It can also be done through help View command :
help @string
help @list
help @hash
help @set
help @sorted_set
For example, to perform :help @string
string Operation commands and usage scenarios
string Common commands
- String common operations
SET key value; -- Store a string key value pair
MSET key1 value1 key2 value2 ... -- Batch store key value pairs
SETNX key value -- Store a string key value pair that does not exist
MGET key1 key2 ... -- Get key values in batch
DEL key1 key2 ... -- Delete key value pair
EXPIRE key seconds -- Set the expiration time of a key ( second )
- Atomic addition and subtraction
INCR key -- take key Add one to the value stored in
DECR key -- take key Subtract one from the value stored in
INCRBY key increment -- take key The value stored in plus increment
DECRBY key decrement -- take key Subtract from the value stored in decrement
Use scenarios
- Single value cache
It's simple , Namely SET key value and GET key - Object caching
- SET user:1 json_value( Object's json Format data )
This cache is easy to operate , But modify a field in the object , You need to query the whole object cache , Deserialization , After the modification , Serialization is stored in . - MSET user:1:name lisi user:1:age 18
MGET user:1:name user:1:age
- Distributed lock
When multiple services operate , have access to SETNX command :
The service process that grabs the lock will be set successfully , If you don't grab it, it will return 0, Delete this key after the business logic processing is completed . - Counter : The amount of reading
INCR article:id;
GET article:id;
- web colony session share
session+redis Realization session share - Distributed system global serial number
INCRBY article 1000 Single acquisition 1000, Lifting performance
hash Operation commands and usage scenarios
Common commands
HSET key field value -- Storage
HGET key field -- Get a field value
HMSET key field1 value1 field2 value2 ... -- Store multiple hash Key value pair
HMGET key field1 field2 ... -- Get multiple hash Key value pair
HSETNX key field value -- Storage one does not exist filed Value , Notice that it's not key
HDEL key field1 field2 ... -- Delete fields
HLEN key -- return key in field The number of
HGETALL key -- Back to all field
HINCRBY key field increment -- by field The value of the increase increment
Use scenarios
- Store the object
HMSET user 1:name zhuge 1:balance 1888
HMGET user 1:name 1:balance
2. E-commerce shopping cart
- Add the goods
HSET cart:[ user id] goods id Number
- Increase the quantity of goods
HINCRBY cart:[ user id] goods id 1
- Total number of commodity categories
HLEN cart:[ user id]
- Delete item
HDEL cart:[ user id] goods id
- Get all the shopping cart items
HGETALL cart:[ user id]
Example :
hash And string Advantages and disadvantages compared with storage objects
- advantage
- Data of the same kind is classified and consolidated , Easy to manage
- comparison string Operation consumes memory and cpu smaller
- Than string Save a space
- shortcoming
- The expired function cannot be used in field On , Can only be used in key On
- redis Cluster architecture is not suitable for large-scale use
list Operation commands and usage scenarios
list Common commands
LPUSH key value1 value2 ... -- Place one or more values from the left key in
RPUSH key value1 value2 ... -- Place one or more values from the right key in
LPOP key -- Pop up values from the left
RPOP key -- Pop up values from the right
LRANGE key start stop -- Returns a list of key The elements in the specified interval , The interval is offset by start and stop Appoint
BLPOP key1 key2 ... [timeout] -- From many list Pop up element on the left in the middle , Timeout time timeout
BRPOP key1 key2 ... [timeout] -- From many list Pop up element on the right in the middle , Timeout time timeout
Use list Building data structures
Stack( Stack ) = LPUSH + LPOP
Queue( queue ) = LPUSH + RPOP
Blocking Queue( Blocking queues ) = LPUSH + BRPOP
Use scenarios
- Micro-blog and official account message flow
Big V Will send messages to subscribed fans :
for example : user hiwei Of id1001
The spare wheel said that the car pushed messages to fans :
LPUSH msg:1001 1888
MacTalk Also send messages :
LPUSH msg:1001 1999
hiwei Get recent messages :
LRANGE msg:1001 0 4 – View the last five messages
set Operation commands and usage scenarios
Common commands
SADD key member1 member2 ... -- towards set Put one or more in value
SREM key member1 member2 ... -- from set Delete element
SMEMBERS key -- from set Get all elements from
SCARD key -- Get collection key The number of elements in
SISMEMBER key member -- Judge member Whether it exists in a set key in
SRANDMEMBER key count -- From the collection key Randomly selected count Elements , Don't delete elements .
SPOP key count -- From the collection key Take them out randomly count Elements , Remove from collection .
set Operation :
SINTER key1 key2 ... -- Intersection operation
SINTERSTORE newKey key1 key2 ... -- take key The intersection of is stored in a new set newKey
SUNION key1 key2 ... -- Union operation
SUNIONSTORE newKey key1 key2 ... -- take key The union of is stored in a new set newKey
SDIFF key1 key2 ... --- Subtraction operation
SDIFFSTORE newKey key1 key2 ... -- take key Save the difference set into a new set newKey
Use scenarios
- Wechat lottery
Users participate in the lottery :
SADD lottery 1001;
SADD lottery 1002;
SADD lottery 1003;
View all lucky draw users :
SCARD lottery;
Draw a lucky man :
SRANDMEMBER lottery 1;
If it's a multiple draw , You can't win multiple awards , Then use SPOP lottery count - give the thumbs-up Collect scenes
jams id=1001,tony Id=1002
- jams Yes tony give the thumbs-up :
SADD like:1002 1001 - tony Check the total number of likes :SCARD like:1002
- View all likes :SMEMBERS like:1002
- jams Cancel likes :SREM like:1002 1001
- Weibo, wechat and other social software attention models
for example :jams、mic、tony、lisi、wangwu
jams Pay attention to the people jamsSet = {lisi,tony}
mic Pay attention to the people micSet = {lisi,wangwu}
be jams and mic People of common concern :SINTER jamsSet micSet;
jams People you may know :SDIFF jamsSet micSet Then remove jams People of concern .
zset Operation commands and usage scenarios
Common commands
ZADD key [[score member]...] -- Assemble in order key Add with score in member
ZREM key member1 member2 ... -- Remove elements
ZSCORE key member -- Returns the element member The score of
ZINCRBY key increment member -- For the elements member The score of plus increment
ZCARD key -- Returns the number of elements in the collection
ZRANGE key start stop -- Positive order returns from start Subscript to stop Subscript elements
ZREVRANGE key start stop -- Return in reverse order from start Subscript to stop Subscript elements
zset Set operations :
ZINTERSTORE destination numkeys key [key ...] -- Intersection calculation
ZUNIONSTORE destkey numkeys key [key ...] -- Union calculation
Use scenarios
Achieve leaderboards
1) Click on news
ZINCRBY hotNews:20190819 1 Guard Hong Kong
2) Top 10 on display day
ZREVRANGE hotNews:20190819 0 9 WITHSCORES
3) Seven days search list calculation
ZUNIONSTORE hotNews:20190813-20190819 7
hotNews:20190813 hotNews:20190814… hotNews:20190819
4) Show the top ten of the seven days
ZREVRANGE hotNews:20190813-20190819 0 9 WITHSCORES
版权声明
本文为[hi wei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220550379482.html
边栏推荐
- TypeError: ‘Collection‘ object is not callable. If you meant to call the ......
- MySQL slow query
- Leetcode 1547: minimum cost of cutting sticks
- Backup MySQL database with Navicat
- 【数据库】MySQL多表查询(一)
- vscode ipynb文件没有代码高亮和代码补全解决方法
- Sword finger offer: push in and pop-up sequence of stack
- Deep learning notes - semantic segmentation and data sets
- Basic theory of Flink
- [database] MySQL basic operation (basic operation ~)
猜你喜欢
Deep learning notes - object detection and dataset + anchor box
[2022 ICLR] Pyramid: low complexity pyramid attention for long range spatiotemporal sequence modeling and prediction
Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
Details related to fingerprint payment
Solve valueerror: argument must be a deny tensor: 0 - got shape [198602], but wanted [198602, 16]
Painless upgrade of pixel series
Sword finger offer: the median in the data stream (priority queue large top heap small top heap leetcode 295)
Restful toolkit of idea plug-in
COM in wine (2) -- basic code analysis
Innovation training (VI) routing
随机推荐
Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
和谐宿舍(线性dp / 区间dp)
Innovation training (IV) preliminary preparation - server
Innovation training (XII) reptile
用LCR表完美测试无线充电系统中的线圈
Golang select priority execution
MySQL uses or to query SQL, and SQL execution is very slow
Basic concepts of multithreading (concurrency and parallelism, threads and processes) and entry cases
Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
Independent station operation | Facebook marketing artifact - chat robot manychat
Agile practice | agile indicators to improve group predictability
机器学习---线性回归
Installing kuberneters using kubedm
[database] MySQL multi table query (I)
This call when the transaction does not take effect
QPushbutton 槽函数被多次触发
Innovation training (VI) routing
Graduation project
Implementation of switching windows and capturing data in selenium mode
C. Tree Infection(模拟+贪心)