基本命令
进入redis
redis-cli -p 端口号 //后边可以接 -n 库号 进入指定库
help命令查看帮助文档
String类型
对于字符串的操作
- append:Append a value to a key
- set/get
- setrange:Overwrite part of a string at key starting at the specified offset
- getrange:Get a substring of the string stored at a key
- strlen:Get the length of the value stored in a key
- mset/mget:Set multiple keys to multiple values / Get the values of all the given keys
- getset:Set the string value of a key and return its old value
对于数值的操作
- incr / incrby / incrbyfloat
- decr / decrby /decrbyfloat
应用场景
抢购,秒杀,详情页,点赞数,评论数等等
可以规避并发下,对数据库事务的操作,完全由redis内存操作来代替,即计算向数据移动。
查看value类型
type key
查看编码类型
object encoding key
二进制安全:采取字节流(不采用字符流),客户端与服务端要规范编码方式
bitmap
- setbit:Sets or clears the bit at offset in the string value stored at key
- bitpos:Find first bit set or clear in a string //这里查找的位置不是某个字节中的索引,而是整个二进制表的索引
- bitcount:Count set bits in a string
- bitop:Perform bitwise operations between strings
ex:bitop and andkey key1 key2 key1和key2做按位与运算得到的结果存放在andkey里
应用场景
-
用户系统,统计用户登录天数,且窗口随机
我们可以试着计算一下,统计一年365天一千万用户的登录情况需要多少空间,365天一共365个二进制位,每个用户占用46个字节,所以大约占用400M空间。 -
假设某团618当天登录就送一份礼物,并且某团有2E用户,那么某团需要多少备货 —— 活跃用户统计
再比如某月1-3号统计登录用户数量,重复登录需要去重,如何做? —— 对上图进行矩阵的转置
–将1-3号作为key,并且把用户id映射到key的二进制位上,用户登录则设置为1
–setbit 20190101 1 1
–setbit 20190102 1 1 setbit 20190102 7 1
–setbit 20190103 7 1
–bitop or result 20190101 20190102 20190103
–bitcount result 0 -1