Redis entry to proficient learning

Getting started with Redis

Redis

Redis is an open source log-type, Key-Value database that is written in ANSI C language, complies with the BSD protocol, supports the network, and can be based on memory and can be persisted.

  • Redis supports data persistence and can store data in memory to disk.
  • Not only supports key-value data, but also supports list, set, zset, hash and other data structures
  • Support data backup

Features of redis

  • Extremely high performance, the reading speed can reach 110,000 times/s; the writing speed can reach 81,000 times/s
  • Support multiple data types
  • All operations are atomic (including multi-step operations)
  • Redis supports persistent memory database persistence to hard disk
  • Redis single process, single thread high efficiency Redis realizes distributed lock

Redis data types and related commands

  • string

A key can store up to 512mb

//存入
set mykey "hello word"
//取出
get mykey
//返回key中的字符串的子字符串
getrange key start end
// 将key的值设为value并返回旧值
getset key value
//对key所存储的字符串,获取指定偏移量上的位
getbit key offset
//获取所有给定key的值
mget key1 [key2...]
//对所有key存储的字符串,设置或清除指定偏移量上的位
setbit key offset value
//将值value关联到key,并将key的过期时间设为seconds
setex key seconds value
//只有在key不存在时设置key的值
setnx key value
//返回key所存储的字符串的长度
srtlen key
//将key中存储的值加一
incr key
//将key所存储的值加上给定的增量值
incrbyfloat key increment
//在key后面追加字符串
append key value
  • Hash is
    suitable for storing objects
// 存入
hmset myhash mykey01 "hello" 
//取出
hget myhash mykey01
// 获取存储在哈希表中指定key的所有字段和值
hgetall key
//为哈希表key中的指定字段的整数值加上增量increment
hincrby key field incremtn
//获取所有哈希表中的字段
hkeys key
//获取哈希表中字段的数量
hlen key
// 将哈希表key中的字段field的值设为value
heset key field value
//只有在字符按field不存在时,设置哈希表字段的值
hsetnx  key field value
// 获取哈希表中所有的值
hvals ksy
  • list list The
    list is a list of strings, sorted according to the order in which they are stored

    //从头部插入
    lpush mylist hello
    //从尾部追加
    rpush mylist word
    //列出
    lange mylist 0 10
    //移除并获取第一个元素 ,如果没有元素会阻塞列表直到等待超时会发现可弹出的元素为止
    blpop key1 [key] timeout
    //移除并获取列表的最后一个元素。如果没有元素则会阻塞列表,直到等待时间超时,或发现可弹出的元素为止。
    brpop key1 [key2] timeout
    //从列表中弹出一值,并将弹出的元素插入到另一个列表中并返回它;如果没有元素则会阻塞直到超时,或发现可以弹出的元素
    brpoplpush source destination timeout
    //通过元素的索引获取列表中的元素
    lindex key index
    //获取列表的长度
    llen key
    //移除列表的第一个原元素
    lpop  key
    //将一个值插入到已存在的列表的头部
    lpushx key value
    //获取列表指定范围内的元素
    lrange key start stop
    //移除列表元素
    lrem key count
    //通过索引设置列表元素的值
    lset key index value
    //让列表只保留指定区间的元素
    Ltrim key start stop
    //移除列表的最后一个元素
    rpop key
    //移除列表的最后一个元素,并将该元素添加到另一个列表并防护
    rpoplpush source destination
    //为列表章添加多个值
    rpush key value1 [value2]
    //为已存在的列表添加值
    rpushhx key value
    
  • The set collection
    is implemented through a hash table, so the complexity of adding, deleting, and searching is all O(1)

    //加入
    sadd myset aaa
    sadd myset bbb
    //列出
    smembers myset
    //获取结合的成员数
    scard key
    //返回指定结合的差集
    sdiff key1 [key2]
    //返回给定集合的差集并存储在destination中
    sinterstore destionation key1 [key2]
    //判断memeber元素是否是集合key的成员
    sismember key member
    //将member从source结合移动到destination集合
    smove source destionation member
    //移除并返回集合中的一个随机元素
    spop key
    //返回集合中的一个或多个随机数
    srandmember key [count]
    //返回给定集合的并集
    sunion key1 [key2]
    
  • zset ordered set
    does not allow duplicate members, each member is associated with a double type score. Sort by score, from smallest to largest

    //加入
    zadd mysset 0 aaa
    zadd mysset 1 bbb
    //列出
    zrangebysocre mysset 0 10
    
    //向有序集合添加一个或多个成员,或者更新已存在成员的分数
    ZADD key score1 member1 [score2 member2]
    
    //获取有序集合的成员数
    ZCARD key
    
    //计算在有序集合中指定区间分数的成员数
    ZCOUNT key min max
    
    //有序集合中对指定成员的分数加上增量 increment
    ZINCRBY key increment member
    
    //计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中
    ZINTERSTORE destination numkeys key [key ...]
    
    //在有序集合中计算指定字典区间内成员数量
    ZLEXCOUNT key min max
    
    //通过索引区间返回有序集合成指定区间内的成员
    ZRANGE key start stop [WITHSCORES]
    
    //通过字典区间返回有序集合的成员
    ZRANGEBYLEX key min max [LIMIT offset count]
    
    //通过分数返回有序集合指定区间内的成员
    ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT]
    
    //返回有序集合中指定成员的索引
    ZRANK key member
    
    //移除有序集合中的一个或多个成员
    ZREM key member [member ...]
    
    //移除有序集合中给定的字典区间的所有成员
    ZREMRANGEBYLEX key min max
    
    //移除有序集合中给定的排名区间的所有成员
    ZREMRANGEBYRANK key start stop
    
    //移除有序集合中给定的分数区间的所有成员
    ZREMRANGEBYSCORE key min max
    
    //返回有序集中指定区间内的成员,通过索引,分数从高到底
    ZREVRANGE key start stop [WITHSCORES]
    
    //返回有序集中指定分数区间内的成员,分数从高到低排序
    ZREVRANGEBYSCORE key max min [WITHSCORES]
    
    //返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序
    ZREVRANK key member
    
    //返回有序集中,成员的分数值
    ZSCORE key member
    
    //计算给定的一个或多个有序集的并集,并存储在新的 key 中
    ZUNIONSTORE destination numkeys key [key ...]
    
    //迭代有序集合中的元素(包括元素成员和元素分值)
    ZSCAN key cursor [MATCH pattern] [COUNT count]
    

Redis key management

  • Delete key

    of the key

  • Serialize the specified key and return the serialized value

    dump key

  • Check if the given ksy exists

    exists key

  • Set the expiration time (seconds) for the specified key

    expire key seconds

  • Set expiration timestamp for the specified key

    expireat key timestamp

  • Find the key that matches the given pattern

    keys pattern

  • Move the key to the specified database

    move key db

  • persist key

    Remove the expiration time of the key

  • Return the remaining expiration time of the key in milliseconds

    pttl key

  • Return the remaining expiration time of the key in seconds

    ttl key

  • Modify the name of the key

    rename key newkey

  • Change the name only when newkey does not exist

    renamenx key newkey

  • Returns the type of the value stored in the key

    type key

Redis HyperLogLog

Used for base statistics. The advantage is that when the amount or volume of data is large, the space for calculating the base is fixed and small.

//添加指定元素到 HyperLogLog 中。
PFADD key element [element ...]

//返回给定 HyperLogLog 的基数估算值。
PFCOUNT key [key ...]

//将多个 HyperLogLog 合并为一个 HyperLogLog 
PFMERGE destkey sourcekey [sourcekey ...]

Publish and subscribe

Redis publish and subscribe is a message communication mode; the sender sends a message, and the receiver receives the message. The redis client can subscribe to any number of channels.
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-BCJlsjyO-1605168552037)(https://s2.ax1x.com/2019/04/17/Az13Xd.png )]

redis transaction

A transaction will go through the following three stages from inception to execution

  • Start business
  • Order to enqueue
  • Execute transaction

Start a transaction with multi and end a transaction with exec.

Related affairs numerology

//取消事务
discard

//执行事务块内的命令
exec

//标记一个事务块的开始
multi

//取消watch命令对所有key的监视
unwatch

//监视指定的key,如果在执行事务之前这些key被其它命令改动则事务被打断
watch

redis connection

//验证密码是否正确
auth password

//打印字符串
echo message

//查看服务是否运行
ping 

//关闭当前连接
quit

//切换到指定的数据库
select index

Redis start service details

Open redis remote link

Persistence mechanism

client redis [memory]-----"memory data-data persistence-"disk

Redis officially provides two different persistence methods to store data in the hard disk:

  • Snapshort
  • AOF (Append Only File) only append log files
Snapshot

1. Features

​ This method can write all data at a certain moment to the hard disk. Of course, it is also the default persistence mode of redis . The saved file is a file ending in .rdb format, so this method is also called RDB mode.

2. Snapshot generation method

  • Client mode: BGSAVE and SAVE instructions
  • Server configuration is automatically triggered

​ 1. BGSAVE in client mode

-A. The client can use the BGSAVE command to create a snapshot. When receiving the BGSAVE command from the client, redis will call fork to create a child process, and then the child process is responsible for writing the snapshot to the disk, while the parent process continues processing Command request

​ ·Term explanation: fork When a process creates a child process, the underlying operating system will create a copy of the process, and the operation of creating a child process in a Unix-like system will be optimized: at the beginning of the division, the parent process is shared The same memory · The sharing of the written memory will not end the service until the parent process or the child process writes the memory

Note: The SAVE command is not commonly used. Before the snapshot is created using the SAVE command, redis is in a blocked state and cannot be serviced externally.

AOF only append log files

springBoot operation Redis

Redis key setting timeout application

Mobile phone number verification

Redis application scenarios

1. Use the string type in redis to complete the implementation of mobile phone verification storage in the project

2. Use the string type in redis to complete the invalid business function 12306 Taobao order also: 40 minutes

3. Use the redis distributed cluster system Session to share memcache memory database storage upper limit data types are relatively simple redis memory data types are rich

4. Use redis zset type to sort the set type element score ranking function dangdang sales ranking sales (Zset) [product id, product sales]

5. Use redis distributed cache implementation

6. Use redis to store token information after authentication, WeChat Mini Program, WeChat Official Account | User openid — "Token (token)

7. Use redis to solve the distributed lock problem in the distributed cluster system redis single process single thread

​ jvm 1 process opens multiple threads synchronize int n=20

​ jvm 1 process opens multiple threads synchronize int n=20

…LRA script

Implementation of Distributed Cache

redis distributed cache (two)

redis distributed cache (three)

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-RkoEqiUn-1605168552079)(http://zhao.zcycomputer.cn/2020-09-05_111224.png)]

Master-slave replication

Redis sentinel mode

Redis cluster

PING —>PONG agreement

principle

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-DPLPJETK-1605168552090)()]

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-9Aq0ubEk-1605168552092)()]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-kuCF7X3F-1605168552096)()]

Redis realizes session sharing management

Code address https://gitee.com/zhanchengyang/learning

Guess you like

Origin blog.csdn.net/lmsfv/article/details/109646412
Recommended