Redis 笔记(03)— string类型(设置key、获取key、设置过期时间、批量设置获取key、对key进行加减、对key值进行追加、获取value子串)

字符串 stringRedis 最简单的数据结构。Redis 所有的数据结构都是以唯一的 key 字符串作为名称,然后通过这个唯一 key 值来获取相应的 value 数据。不同类型的数据结构的差异就在于 value 的结构不一样。

Redis 的字符串是动态字符串,是可以修改的字符串,内部结构实现上类似于 JavaArrayList,采用预分配冗余空间的方式来减少内存的频繁分配,
string
如图中所示,内部为当前字符串实际分配的空间 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> 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值