当前位置:网站首页>Redis basic knowledge, let's review it
Redis basic knowledge, let's review it
2022-07-28 08:41:00 【Chon.Wang】
# Preface
Redisyeskey-valueThe storage system , It's cross platform Non relational database . Point me into the Redis Official website .
RedisSupport data persistence , The data in memory can be saved periodically in disk files , Recoverable for reuse .
RedisSupportString、list、set、Zset、hashAnd other data structures
RedisCan be used to do Cache of data 、 Ranking of data 、 Message queue Such as the scene
I don't say much nonsense , The basics begin .
One 、 Installation and configuration
Here are just a few Linux Source code installation .
1.1 Linux install Redis
# install
# download redis The latest stable source file
wget https://download.redis.io/redis-stable.tar.gz
# decompression
tar -zxvf redis-stable.tar.gz
# Entry directory
cd redis-stable
# compiling make
make
# Execution and installation
make install PREFIX=/usr/local/redis
# Check whether the installation is successful , bin If the directory exists, the installation succeeds
cd /usr/local/redis
1.2 Redis Server startup
1.2.1 preparation
# 1. Enter the unzipped directory just now , Copy redis.conf File to the installation directory bin Directory
cp /root/redis-stable/redis.conf /usr/local/redis/bin
# 2. modify redis.conf
vim redis.conf
# 3. Input / Get into vim Last row mode , Search for daemonize, Turn daemon mode on
# 4. take daemonize Change it to yes
# 5. vim Save and exit
1.2.2 start-up redis Server side
# 1. Get into /usr/local/redis/bin
cd /usr/local/redis/bin
# 2. With redis.conf File is configuration file , start-up redis
./redis-server redis.conf
# 3. Check to see if startup succeeded
ps -ef | grep redis
1.2.3 close redis Server side
# Kill process
kill -9 redis The process of ID
# close redis service
./redis-cli shutdown
1.3 Redis The configuration file
# Just list some common configurations
vim /usr/local/redis/bin/redis.conf
# The following is the configuration content
daemonize no|yes # Whether to open the daemon to run
pidfile /var/run/redis_6379.pid # When the daemon is turned on , By default pid write in /var/run/redis_6379.pid in
port 6379 # redis Default listening port
bind 127.0.0.1 # The default bound host IP
timeout 300 # The connection will be closed after the client is idle for the longest time , Set to 0 It means that the function is turned off
databases 16 # Default 16 Number of databases , The default is 0 database
maxclients 128 # Set the maximum number of client connections at the same time , Default limit
Two 、 Redis data type
Redis There are five types of data : character string (strings)、 Hash (hashes)、 list (lists)、 aggregate (sets)、 Ordered set (sorted sets).
# Start again redis , Entry directory
cd /usr/local/redis/bin
# start-up redis Server side
./redis-server redis.conf
# start-up redis client
./redis-cli
# The following command needs to be in Redis Client operation
2.1 character string (strings)
The string is
redisBasic 、 Common types , OnekeyCorresponding to onevalueThe maximum value cannot be greater than 512 MB
It can be saved character string 、json、 binary data 、 picture 、 Serialize values, etc
Application scenarios : Cache basic data 、 Counter, etc
Common commands :
exists、set、get、mset、mget、del、append、decr、incr、decrby、incrby、incrbyfloat、strlen、、、、、、、``、
# redis-cli Client command line
# 1. Whether there is a key name : exists Key name
exists name # 0
# 2. Set individual : set Key name value
set name Chon
# 3. Get a single : get Key name
get name
# 4. Set up multiple : mset Key name 1 value 1 Key name 2 value [ Key name n value n]
mset domain bqhub.com author Chon
# 5. Get multiple : mget Key name 1 Key name 2 [ Key name n]
mget domain author
# 6. Delete : del Key name
del name
# 7. Additional : append Key name value
set name Chon # So let's set up a
append name Wang # Additional
get name # Output : ChonWang
# 8. Minus one ( Integers ): decr Key name
set age 18 # Set a value to a number
decr age # Output minus 1 After the value of 17
# 9. Add one ( Integers ): incr Key name
set height 180 # Set a value to a number
incr height # Output plus 1 After the value of 181
# 10. Subtraction ( Integers ): decrby Key name step
set age 18 # Set a value to a number
decrby age 10 # Output minus 10 After the value of 8
# 11. Add ( Integers ): incrby Key name step
set height 180 # Set a value to a number
incrby height 10 # Output plus 10 After the value of 190
# 12. Add ( Floating point numbers ): incrbyfloat Key name step
set weight 65.2 # Set a value to a number
incrbyfloat weight 1.3 # Output plus 1.3 After the value of 66.5
# 13. Get value length : strlen Key name
strlen domain
2.2 Hash (hashes)
- A hash is a collection of key value pairs (key=>value)
- Often used to save
object- Application scenarios :
- Common commands
hset、hget、hmset、hmget、hdel、hgetall、hkeys、hvals、hlen、hstrlen、hexists
# redis-cli Client command line
# 1. Single data operation
# Set individual : hset Key name Field name value
hset bqhub domain bqhub.com
# Get a single : hget Key name Field name
hget bqhub domain
# 2. Multiple data operations
# Set up multiple : hmset Key name Field name 1 value 1 Field name 2 value 2 [ Field name n value n]
hmset bqhub domain bqhub.com author Chon
# Get multiple : hmget Key value Field name 1 [ Field name n]
# Return array format display
hmget bqhub domain author
# Removing a single : hdel Key name Field name [ Field name n value n]
hdel bqhub domain author
# 3. Get all the data ( Key name and value ): hgetall Key name
hgetall bqhub
# 4. Get all field names : hkeys Key name
hkeys bqhub
# 5. Get all values : hvals Key name
hvals bqhub
# 6. Get the number of fields : hlen Key name
hlen bqhub
# 7. Get the length of the field value : hstrlen Key name Field name
hstrlen bqhub domain
# 8. Whether this field exists , If the key name does not exist , Also returned 0
hexists bqhub domain # 1
hexists bqhub name # 0
hexists aaaaa sex # 0
2.3 list (lists)
- Lists are linked results , Sort in the order of insertion , Elements can be inserted or popped from both ends .
- Application scenarios : example : Left in right out message queue
- Common commands :
lpush、lpushx、rpush、rpushx、linsert、lrange、lindex、lpop、blpop、rpop、brpop、lrem、ltrim、lset、llen
# 1. Insert... On the left ( If the list does not exist, create ): lpush List name value1 [value...]
lpush testLpush v1 v2 v3
# 2. Insert... On the left ( The list doesn't exist , No operation ): lpushx List name value1 [value...]
lpushx testLpush v4 # success
lpushx aaa a1 # Failure , because aaa list non-existent
# 3. Insert... On the right ( If the list does not exist, create ): rpush List name value1 [value...]
rpush testRpush v1 v2 v3
# 4. Insert... On the right ( The list doesn't exist , No operation ): rpushx List name value1 [value...]
rpushx testRpush v4 # success
rpushx bbb b1 # Failure , because bbb list non-existent
# 5. Insert a new element before or after the element : linsert List name before|after Existing element values New element value
linsert testLpush before v2 v22
linsert testLpush after v3 v33
# 6. Query list : lrange List name Start index End index
# 0 1 It's No One Two Elements , -1 -2 Is the penultimate Two elements , And so on
lrange testLpush 0 -1
# 7. Query element : Get elements from index : lindex List name Indexes
lindex testLpush 1
# 8. The first element on the left pops up : lpop List name
lpop testLpush
# 9. The first element on the left pops up : blpop List name Timeout seconds
# If the list is empty , Then wait for the timeout to stop or the element is found within the timeout and pop up
blpop testLpush 3
# 10. The first element on the right pops up : rpop List name
rpop testRpush
# 11. The first element on the right pops up : brpop List name Timeout seconds
# If the list is empty , Then wait for the timeout to stop or the element is found within the timeout and pop up
brpop testRpush 3
# 12. Delete a certain number of elements : lrem List name Number Elements
# > 0 Left to right
# < 0 From right to left
# = 0 Delete all
lrem testLpush 2 'v3'
# 13. Keep elements in a certain range : ltrim List name Start index end fqxh
ltrim testLpush 1 4 # Keep only the index 1 To 4 The elements of , Delete all others
# 14. Replace the value of an index : lset List name Indexes The new value
lset testLpush 1 'v11'
# 15. Get the length of the list : llen List name
llen testLpush
2.4 unordered set (sets)
- A collection of string elements
- Duplicate elements are not allowed
- unordered set , No subscript
- Application scenarios : Tags contain articles 、 Aggregation of fans concerned by users
- Common commands :
sadd、scard、sdiff、sdiffstore、sinter、sinterstore、sunion、sunionstore、sismember、smismember、smembers、srandmember、smove、spop、srem
# 1. Add elements... To the collection : sadd Collection name value1 [value...]
sadd myset 1 2 3 4 5 6
# 2. Get the total number of collection elements : scard Collection name
scard myset
# 3. Difference set : sdiff Gather one Set two [ aggregate n]
# Only get the difference set between the first set and subsequent sets
sadd setnum 1 2 3 11 12 13
sdiff myset setnum # return 4 5 6
# 4. Save difference : sdiffstore New collection name Compare sets 1 More collective 2 [ Compare sets n]
sdiffstore diffset myset setnum # Save the difference set to diffset In new collection
# 5. intersection : sinter Gather one Set two [ aggregate n]
# Returns the intersection of all sets
sinter myset setnum # return 1 2 3
# 6. Intersection save : sinterstore New collection name Compare sets 1 More collective 2 [ Compare sets n]
sinterstore interset myset setnum # Save the intersection to interset In new collection
# 7. Combine : sunion Gather one Set two [ aggregate n]
# Returns the union of all sets
sunion myset setnum
# 8. Union save : sunionstore New collection name Compare sets 1 More collective 2 [ Compare sets n]
sunionstore unionset myset setnum # Save union to unionset In new collection
# 9. Whether elements exist : sismember Collection name value
sismember myset 1 # 1
sismember myset 100 # 0
# 10. Whether multiple elements exist : smismember Collection name value1 value2 [value...]
smismember myset 1 2 100 200
# 11. Get all the elements : smembers Collection name
smembers myset
# 12. Random return n Elements : srandmember Collection name Number n
srandmember myset 2 # Returns two elements at random
# 13. Move element to new collection : smove The original assembly New collection value
smove myset setnum 5
# 14. Remove randomly n Elements : spop Collection name Number n
spop myset 2 # Remove randomly 2 Elements , And return these two elements
# 15. Remove an element : srem Collection name value
srem myset 1
2.5 Ordered set (Sorted Set)
- A collection of string elements
- Duplicate elements are not allowed
- Orderly sorting , The default order is from small to large
- Set a score for each element , The scores can be the same , Sort by score
- Application scenarios : Ranking list of various rules
- Common commands :
zadd、zrandmember、zrange、zrangestore、zrangebyscore、zrank、zscore、zmscore、zcard、zcount、zrevrange、zrevrangebyscore、zrevrank、zmpop、zpopmax、zpopmin、zrem、zremrangebyrank、zremrangebyscore、zdiff、zdiffstore、zunion、zunionstore、zinter、zinterstore、zintercard、zincrby
# 1. Add or update elements : zadd Collection name [ Options ] fraction 1 value 1 fraction 2 value 2 [...]
# Common options
# xx : Only update without adding
# nx : Only add without updating
# lt : New score lower than The current score is only updated , Reinsert the correct sort position after update
# gt : New score Greater than The current score is only updated , Reinsert the correct sort position after update
zadd myzset 98 yuwen 112 shuxue 102 yingyu 91 wuli 98 zhengzhi
# 2. Get elements - Randomly returned n individual : zrandmember Collection name Number n [withscores]
zrandmember myzset 2 withscores # Returns two elements at random , And show the score
# 3. Get elements - According to the index range : zrange Collection name Start index End index [withscores]
# 0 1 It's No One Two Elements , -1 -2 Is the penultimate Two elements , And so on
zrange myzset 0 -1 withscores
# 4. Get elements - According to the index range - Save to new collection : zrangestore New collection name Original set name Start index End index
# 0 1 It's No One Two Elements , -1 -2 Is the penultimate Two elements , And so on
zrangestore new_myzset myzset 2 -1
# 5. Get elements - According to the score range : zrangebyscore Collection name Minimum score Maximum score [withscores]
zrangebyscore myzset 95 105 withscores
# 6. Get index subscript - According to element value : zrank Collection name value
zrank myzset shuxue
# 7. Get a single score - According to element value : zscore Collection name value
zscore myzset shuxue
# 8. Get multiple scores - According to element value : zmscore Collection name value1 value2 [value...]
zmscore myzset shuxue yingyu
# 9. Get the total number of elements : zcard Collection name
zcard myzset
# 10. Get the number of elements - According to the score range : zcount Collection name Minimum score Maximum score
zcount myzset 95 105
# 11. Get elements - According to the index range - Sort from large to small : zrevrange Collection name Start index End index [withscores]
zrevrange myzset 0 2 withscores
# 12. Get elements - According to the score range - Sort from large to small : zrevrangebyscore Collection name Maximum score Minimum score [withscores]
zrevrangebyscore myzset 105 60 withscores
# 13. Get index subscript - According to element value - Sort from large to small : zrevrank Collection name value
zrevrank myzset shuxue
# 14. Remove the largest or smallest element : zmpop Number of sets aggregate 1 aggregate 2 [ aggregate n] min|max [count Number ]
zmpop 1 myzset max 2 # Pop up the two largest elements
# 15. Remove the largest element : zpopmax Collection name
zpopmax myzset
# 16. Remove the smallest element : zpopmin Collection name
zpopmin myzset
# 17. Remove elements - According to the element : zrem Collection name value
zrem myzset shuxue
# 18. Remove elements - According to the index range : zremrangebyrank Collection name Start index End index
zremrangebyrank myzset 0 2
# 19. Remove elements - According to the score interval : zremrangebyscore Collection name Minimum score Maximum score
zremrangebyscore myzset 0 60
# 20. Difference set : zdiff Number of sets aggregate 1 [ aggregate n] [withscores]
# Only get the difference set between the first set and subsequent sets
zdiff 2 myzset myzset1
# 21. Save difference : zdiffstore New collection name Number of sets aggregate 1 aggregate 2 [ aggregate n] [withscores]
zdiffstore diffzset 2 myzset myzset1 # Save the difference set to diffzset In new collection
# 22. Combine : zunion Number of sets aggregate 1 aggregate 2 [ aggregate n] [withscores]
# Returns the union of all sets
zunion 2 myzset myzset1
# 23. Union save : zunionstore New collection name Number of sets aggregate 1 aggregate 2 [ aggregate n]
zunionstore unionzset myzset myzset1 # Save union to unionzset In new collection
# 24. intersection : zinter Number of sets aggregate 1 aggregate 2 [ aggregate n] [withscores]
zinter 2 myzset myzset1
# 25. Intersection save : zinterstore New collection name Number of sets aggregate 1 aggregate 2 [ aggregate n]
zinterstore interzset 2 myzset myzset1 # Save the difference set to interzset In new collection
# 26. The number of intersections : zintercard Number of sets aggregate 1 aggregate 2 [ aggregate n]
zintercard 2 myzset myzset1
# 27. Add ( Integers ): zincrby Collection name Points to be added Element value
zadd my 180 height # Set a value to a number
zincrby my 2 height # Output plus 2 After the value of 182
3、 ... and 、Redis Business
RedisMultiple commands can be executed at one time .RedisBulk operation is sendingexecThe command is put into the queue cache before , Waiting for execution .- Because it has been put into the queue cache , Therefore, operations outside the transaction will not change the data inside the transaction .
- received
execExecute the operation after the command , If the command format is incorrect , Do not perform , If there is no mistake , execute , Even if one command fails , The rest of the commands are still executed .
RedisThere are three stages from the beginning to the end of a transaction : Start business 、 Order to join the team 、 Perform transactions
3.1 Redis Transaction related orders
# 1. Monitor one or more key, If before the transaction is executed , relevant key Altered by other orders , Then the transaction will be interrupted and not executed
watch key1 key2 [key...]
# 2. Mark the beginning of the transaction block
multi
# 3. Execute commands within all transaction blocks
exec
# 4. Cancel the business , Give up executing all commands in the current transaction block
discard
# 5. Cancel watch Command to all key Surveillance
unwatch
3.2 Case affairs
# Case study , In business , The successful execution of the statement returns QUEUED
set coll_num 10
watch coll_num # monitor Collect the number
multi # Open transaction
incr coll_num # Self increase 1,
exec
unwatch
Four 、 Commonly used Redis Server command
# 1. obtain Redis All statistics
info
# 2. Set the current connection name
client setname testClient
# 3. Get the current connection name
client getname
# 4. Clear the current connection name
client setname ""
# 5. Get the current server time
time
# 6. Delete the key
flushall
# 7. Delete the key
flushdb
# 8. Real time printing Redis Commands received by the server
monitor
# 9. Save data to hard disk
save
# 10. See if the service is running
ping
# 11. Switch to the specified database . I mentioned before , Default 16 Number of databases , The default is 0 database : select index
select 3 # Switch to 3 database
# 12. Close the current connection
quit
边栏推荐
- Simple use of unity queue
- ciou损失
- 说透缓存一致性与内存屏障
- Can‘t connect to server on ‘IP‘ (60)
- How does QT delete all controls in a layout?
- Opencv+paddle Orc recognize pictures and extract table information
- PHP基础知识 - PHP 使用 PDO
- C轮融资已完成!思迈特软件领跑国内BI生态赋能,产品、服务竿头一步
- C#,入门教程——程序运行时的调试技巧与逻辑错误探针技术与源代码
- Analysis of model predictive control (MPC) (IX): numerical solution of quadratic programming (II)
猜你喜欢

Ciou loss

Export SQL server query results to excel table

2022 Niuke multi school second problem solving Report

快速搭建一个网关服务,动态路由、鉴权的流程,看完秒会(含流程图)

NDK 系列(6):说一下注册 JNI 函数的方式和时机

【OpenCV】生成透明的PNG图像

Use of tkmapper - super detailed

Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support

本人男,27岁技术经理,收入太高,心头慌得一比

leetcode刷题,我推荐B站这个妹子学霸的视频
随机推荐
How to use QT help documents
Window 2 - > toolbar (28-1)
(13) Simple temperature alarm device based on 51 single chip microcomputer
opengauss同步状态疑问
GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
Service current limiting and fusing of micro service architecture Sentinel
oracle sql 问题
思迈特软件完成C轮融资,让BI真正实现“普惠化”
Use of tkmapper - super detailed
Maximum product of leetcode/ word length
leetcode/数组中和为0的三个不同数
Can‘t connect to server on ‘IP‘ (60)
One key switch circuit
Does gbase 8s support storing relational data and object-oriented data?
Use of namespaces
Sliding screen switching on uniapp supports video and image rotation, similar to Tiktok effect
创建线程的3种方式
QT 怎么删除布局里的所有控件?
模型预测控制(MPC)解析(九):二次规划的数值解(下)
Usage of qmap