字符串 string
是 Redis
最简单的数据结构。Redis
所有的数据结构都是以唯一的 key
字符串作为名称,然后通过这个唯一 key
值来获取相应的 value
数据。不同类型的数据结构的差异就在于 value
的结构不一样。
Redis
的字符串是动态字符串,是可以修改的字符串,内部结构实现上类似于 Java
的 ArrayLis
t,采用预分配冗余空间的方式来减少内存的频繁分配,
如图中所示,内部为当前字符串实际分配的空间 capacity
一般要高于实际字符串长度 len
。当字符串长度小于 1M 时,扩容都是加倍现有的空间,如果超过 1M,扩容时一次只会多扩 1M 的空间。需要注意的是字符串最大长度为 512M。
1. string 类型相关命令
命令 | 说明 |
---|---|
set key value | 设置key对应值为string类型的value |
setex key seconds value | 设置key对应值为string类型的value,增加到期时间 |
mset key1 value1…keyN valueN | 一次设置多个key的值 |
mget key1 …keyN | 一次获取多个key的值 |
incr key | 对key的值++操作,并返回新值 |
decr key | 同上,但是做的是–操作 |
incrby key integer | 同incr,加指定值 |
decrby key integer | 同desr,减指定值 |
incrbyfloat key increment | 对key的值增加一个浮点数 |
append key value | 给指定key的字符串追加value |
substr key start end | 返回截取过的key的字符串值 |
getrange key start end | 获取存储在key上的值的一个子字符串 |
setrange key offset value | 将从start偏移量开始的子串设置指定的值 |
2. 使用示例
- 键值对
可以对 key
设置过期时间,到点自动删除,这个功能常用来控制缓存的失效时间。
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> set a "this is a string type"
OK
127.0.0.1:6379> setex tmp 5 "tmp"
OK
127.0.0.1:6379> ttl tmp
(integer) 1
127.0.0.1:6379> ttl tmp
(integer) -2
127.0.0.1:6379> ttl tmp
(integer) -2
127.0.0.1:6379> keys *
1) "a"
- 批量键值对,节省网络耗时开销
127.0.0.1:6379> mset b "this is second string" c "third string" d "fourth string"
OK
127.0.0.1:6379> keys *
1) "c"
2) "b"
3) "a"
4) "d"
127.0.0.1:6379> mget a b c d
1) "this is a string type"
2) "this is second string"
3) "third string"
4) "fourth string"
- 计数
如果value
值是一个整数,还可以对它进行自增操作。自增是有范围的,它的范围是signed long
的最大最小值,超过了这个值,Redis
会报错。
127.0.0.1:6379> incr a
(error) ERR value is not an integer or out of range
127.0.0.1:6379> set num 1
OK
127.0.0.1:6379> incr num
(integer) 2
127.0.0.1:6379> get num
"2"
127.0.0.1:6379> decr num
(integer) 1
127.0.0.1:6379> get num
"1"
127.0.0.1:6379> incrby num 10
(integer) 11
127.0.0.1:6379> get num
"11"
127.0.0.1:6379> decrby num 2
(integer) 9
127.0.0.1:6379> get num
"9"
127.0.0.1:6379> incrbyfloat num 0.2
"9.2"
127.0.0.1:6379> get num
"9.2"
127.0.0.1:6379> get a
"this is a string type"
127.0.0.1:6379> append a ", first string"
(integer) 35
127.0.0.1:6379> get a
"this is a string type, first string"
127.0.0.1:6379> substr a 23 -1
"first string"
127.0.0.1:6379> getrange a 23 -1
"first string"
127.0.0.1:6379> get d
"fourth string"
127.0.0.1:6379> setrange d 7 "china"
(integer) 13
127.0.0.1:6379> get d
"fourth chinag"
127.0.0.1:6379> setrange d 7 "chinese"
(integer) 14
127.0.0.1:6379> get d
"fourth chinese"
127.0.0.1:6379>