Redis字符串API
字符串键值结构
key:对于redis而言所有的key都是一个字符串
value:实际可以为字符串、数字、二进制、json串
字符串的value最大限制为512MB,其实已经足够大了,实际使用最好不要过大,建议在100k以内。

字符串使用场景

还有很多很多应用场景,只要你掌握了这样的API就可以结合你的应用场景进行思考,然后进行API的选用来实现你的功能。
字符串常用命令

get、set、del命令演示

incr、decr、incrby、decrby命令演示

简单实战
记录网站每个用户个人主页的访问量
incr userid:pageview
(单线程 : 无竞争)
redis是天然适合做计数器的,因为是单线程的,所以并发执行incr的时候不会有竞争问题,无论并发量多大都不会记错数。
很多网站或者应用会使用incr或者decr这样的命令来做计数器,非常简单但是非常实用。
缓存视频的基本信息(数据源在MySQL中)伪代码
public VideoInfo get(long id){
String redisKey = redisPrefix + id;
//这里省略了反序列化的步骤
VideoInfo videoInfo = redis.get(redisKey);
if (videoInfo == null){
videoInfo = mysql.get(id);
if (videoInfo != null){
//序列化并存储到redis
redis.set(redisKey, serialize(videoInfo));
}
}
return videoInfo;
}
分布式id生成器
incr id
(原子操作)
分布式id生成器,即多个应用并发访问获取的id是自增且不重复的,仍然可以使用incr这样的命令来实现,当然实际的实现方案会比这个要复杂一些,但是最基础的一个实现的思路或者原理都是使用这样一个规则。

其他命令
setnx、setxx、setex

其实这些都是set命令及选项的组合,使用这种组合命令好处是将多个操作作为一个原子操作来执行,就不会存在并发竞争的问题,在实现一些场景比如分布式锁是非常有用的。

mget、mset

mget和mset是批量操作,时间复杂度都是o(n),是非常方便且能提高性能的命令,但是一定要节制去使用。
使用时需要注意的是对于大数据量的获取,最好将其拆分成多个mget操作,例如获取10万个key操作,每次获取1000个,执行100次mget操作。

n次get命令 = n次网络时间 + n次命令时间

1次mget操作 = 1次网络时间 + n次命令时间

这里需要注意的是网络时间,因为客户端和服务端通常是在不同机器甚至是不同的机房、不同的地区,所以网络时间通常是一个很大的开销,而命令本身开销是非常小的,redis大部分命令执行速度都非常快,那么网络时间就显得非常珍贵。
所以使用mget这样的操作可以省去大量的网络时间。在很多场景下它的效率是非常高的,当然如果网络时间越长、获取key的个数越多效果越明显。
查缺补漏

getset、append、strlen
其中strlen
命令的时间复杂度也是o(1),redis字符串内部也会对字符串长度进行实时更新,不需要遍历字符串来计算完整的长度。

incrbyfloat、getrange、setrange

常用命令总结
