Loading

Redis数据结构-string

Redis数据结构-string

字符串

字符串是最基本的数据结构,字符串的值实际可以是字符串(简单的字符串,json,xml),数字(整数,浮点数),甚至是二进制(图片,音频,视频),但是值最大不超过512MB。

灵活使用string可以做很多事情,比如播放量计数,缓存,限速等等

基础命令

设置值

set key value [ex seconds] [px milliseconds] [nx|xx]
-------------------------------------------------------
> set hello world
-------------------------------
选项说明:
ex seconds: 为键设置秒级过期时间
px milliseconds 为键设置毫秒级过期时间
nx:键必须不存在,才可以设置成功,用于添加
xx:键必须存在,才可以设置成功,用于更新

set xx的例子:

> exists hello
0
> set hello world xx
null
> set hello world
OK
> set hello redis xx
OK
> get hello
redis

与ex和nx类似的还有两个单独的命令:setex 和 setnx

setex key seconds value // 设置过期时间,秒级
setnx key value // 键不存在才能添加

setnx的例子:

> exists hello
0
> setnx hello world
1
> setnx hello world
0

由于Redis是单线程的命令处理机制,如果多个客户端同时执行setnx,那么只有一个客户端可以设置成功,所以setnx可以作为分布式锁的实现方案。

【专题todo 分布式锁】

获取值

get key

如果键不存在,返回空(null)

批量设置值

mset key value [key value ...]
-----------------------------------
> mset a 1 b 2 c 3 d 4
OK
> get a
1
> get b
2

批量获取值

mget key [key ...]
-------------------------
> mget a b c r d
1
2
3
null
4

返回的结果是和传入键的顺序一致的.

批量操作减少IO次数,但是要注意批量操作的数量过多可能会阻塞Redis或网络拥塞

计数

整数自增
incr key 
----------------
> incr akey  // 自增不存在的key,按照从0自增,返回1
1
> incr akey // value是整数,返回自增后的结果
2

> set hello world 
OK
> incr hello  // 值非整数,返回错误
ERR value is not an integer or out of range
整数自减
decr key
自增指定数字
incrby key increment
--------------------
> incrby key 2
2
自减指定数字
decrby key decrement
-------------------
> decrby key 2
1
自增浮点数
incrbyfloat key increment
--------------------------
> incrbyfloat key 1.1
2.1

追加值

向字符串尾部添加值

append key val
--------------------
> set hello world
OK
> get hello
world
> append hello 111
8
> get hello
world111

字符串长度

strlen key
--------------------
> strlen hello
8

设置并返回原值

getset key new_val
----------------------
> getset hello redis
world111

设置指定位置的字符

setrange key offset val
-------------------------
> get hello 
redis
> setrange hello 0 R
5
> get hello
Redis

将redis改成了Redis

获取部分字符串

getrange key start end
------------------------
> getrange hello 0 3
Redi

左闭右闭

内部编码

Redis每一种数据结构都有不同的内部实现,string就有三种实现:int,embstr,raw.,可以通过

object encoding key 来查看内部编码。这样设计的好处是,可以根据不同的场景用不同的内部编码,另外可以在不改变API的情况下优化内部实现。

  • int:8个字节的长整型
  • enbstr:小于等于39个字节的字符串
  • raw:大于39个字节的字符串

典型使用场景

缓存

经典的缓存功能,比如一些热点数据缓存到redis。

同时要考虑和持久层的双写一致性问题,需要根据业务选择不同的策略。[todo 写策略]

计数

文章的阅读量,视频的播放量等,可以利用string的incr实现

共享Session

分布式的Web服务器会将用户的Session信息保存到自己的服务器上,如果要服务器之间共享Session,可以将Session用Redis统一管理

限速

比如限制某个接口1分钟之内同一个IP最多访问n次的功能,可以用string的计数来实现。

posted @ 2021-06-07 01:05  非凡岁月  阅读(83)  评论(0编辑  收藏  举报