Redis基础类型
Redis特点
开源的,BSD许可高级的key-value存储系统
可以用来存储字符串,哈希结构,链表,集合
安装
windows:https://github.com/microsoftarchive/redis/releases
mac\linux:
Redis 数据类型
Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(有序集合)。
string(字符串)
字符串类型是Redis的最基本数据结构。
字符串类型的值实际可以为字符串,数字,二进制,但是值最大不能超过512M。
key value
hello world
counter 1
bits 10000100
json {"id":1,"name":"xiaocai","age":18}
string命令
设置
set key value [EX seconds] [PX milliseconds] [NX|XX]
get key
set
name xiaocai
OK
get
name
"xiaocai"
过期
setex key seconds value
set
name1 redis1 ex
10
OK
get
name1
(
nil
)
setex name2
10
redis2
OK
get
name2
"redis2"
get
name2
(
nil
)
set
name3 redis3 px
10
OK
get
name3
(
nil
)
不存在才能设置成功或者必须存在才能设置成功
set
hello world nx
OK
set
hello w nx
(
nil
)
get
hello
"world"
set
hello w xx
OK
set
world hello xx
(
nil
)
get
hello
"w"
get
world
(
nil
)
批量设置
mset key value
[
key value
...]
mget key
[
key
...]
mset name1 redis1 name2 redis2
OK
mget name1 name2
1
)
"redis1"
2
)
"redis2"
mget name1 name2 name3
1
)
"redis1"
2
)
"redis2"
3
)
(
nil
)
计数
incr key
incrby key increment
set
age
18
OK
incr age
(
integer
)
19
incrby age
5
(
integer
)
14
incrby age
10
(
integer
)
24
删除
del key [key ...]
del
age
(
integer
)
1
get
age
(
nil
)
内部编码
int 8个字节的长整型
embstr 小于等于39个字节的字符串
raw 大于39个字节的字符串
set
port
6379
OK
object
encoding port
"int"
set
hello world
OK
object
encoding hello
"embstr"
set
longString abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
OK
object
encoding hello
"raw"
strlen longString
(
integer
)
52
list(列表)
list类型是用来存储多个有序的字符串。每列字符串称之为元素。一个list的最大存储为2^32-1个元素。可以对列表进行双端插入和弹出,也可以指定索引下标获取元素。
列表
list命令
头部和尾部添加元素
lpush key value [value ...]
rpush key value [value ...]
lrange key start stop
lpush letter
"a"
(
integer
)
1
lpush letter
"b"
(
integer
)
2
lpush letter
"c"
(
integer
)
3
lrange letter
0
1
1
)
"c"
2
)
"b"
3
)
"a"
rpush letter
"a"
(
integer
)
4
rpush letter
"b"
(
integer
)
5
rpush letter
"c"
lrange letter
0
1
1
)
"c"
2
)
"b"
3
)
"a"
4
)
"a"
5
)
"b"
6
)
"c"
头部和尾部弹出元素
lpop key
rpop key
lpop letter
"c"
lpop letter
"b"
lrange letter
0
1
1
)
"a"
2
)
"a"
3
)
"b"
4
)
"c"
rpop letter
"c"
rpop letter
"b"
lrange letter
0
1
1
)
"a"
2
)
"a"
索引操作
索引需要对全部list进行遍历,性能会随着元素个数的增大而变差
lrange key start stop
lindex key index
ltrim key start stop
len key
rpush letter b c
(
integer
)
4
lrange letter
0
1
1
)
"a"
2
)
"a"
3
)
"b"
4
)
"c"
lindex letter
2
"b"
ltrim letter
0
2
OK
lrange letter
0
1
1
)
"a"
2
)
"a"
3
)
"b"
llen letter
(
integer
)
3
插入
insert key BEFORE|AFTER pivot value
linsert letter before b c
(
integer
)
4
linsert letter after a d
(
integer
)
5
lrange letter
0
1
1
)
"a"
2
)
"d"
3
)
"a"
4
)
"c"
5
)
"b"
修改
set key index value
lset letter
2
B
OK
lrange letter
0
1
1
)
"a"
2
)
"d"
3
)
"B"
4
)
"c"
5
)