wangduanduan / wangduanduan.github.io

Wubba Lubba dub-dub
https://wdd.js.org
27 stars 7 forks source link

技术之巅:Redis简明史 #236

Closed wangduanduan closed 5 years ago

wangduanduan commented 5 years ago

想要全面理解和掌握一门技术,关键在于弄清楚它的历史、本质和局限性。

Redis历史

时间回到2009年,坐标意大利-西西里。33岁的程序员Salvatore Sanfilippo正在搞一个实时日志分析的服务

下图这张图片来自https://www.eu-startups.com/2011/01/an-interview-with-salvatore-sanfilippo-creator-of-redis-working-out-of-sicily/

Salvatore-Sanfilippo

“WTF,MySql写的速度怎么这么慢。我只想用最快的速度把数据写进去,并且要最快的速度把最新的几条日志获取出来。” Sanfilippo生气的说道,然后深吸一口气,一根烟顿时燃掉了半截。

The web application of lloogg was an ajax app to show the site traffic in real time. So what I needed was a DB handling fast writes, and fast ”get latest N items” operation. If you are a programmer, you know how a linked list can solve this kind of problems, so I started wondering, why on the earth is so hard to model this with MySQL with decent performance? Why there is no database that is able to natively handle natural ordering of items, that is, I put things inside with this order, so it should be fast to get the latest N items. After this considerations I started coding a prototype of the system, and shared the first beta on Hacker News, receiving good feedbacks.

Another reason for using Redis is the following. In the field of programming languages there is a motto: A programming language is worth learning if it is different enough from all you already know to change your mind, exposing you to new abstractions. Well I think Redis definitely is a really different database, and will change the way you think at your data.

Redis数据结构

Redis(Remote Dictionary Server), 从名字上可以看出Redis是远程字典服务器,这个解释更加地道。

Redis是高性能的内存数据库,其数据结构仅有5种。并且这5种数据结构都是建立在STRING结构的基础上。

不同的数据结构有不同的操作命令,但是DEL, TYPE, RENAME这三个命令,对于这5种数据类型都有效。

在5中数据结构中,关键在于理解STRING类型,因为其他四种类型都是STRING类型的组合。STRING表面上看起来是字符串,实际上它不仅仅包含字符串,还包括数值类型的整数和浮点数

结构类型 读写能力
STRING 字符串,整数,浮点数 - 对于数值类型,可以执行自增或者自减
- 对于字符串可以对其整体或者部分进行操作
LIST 一个链表,链表的每个节点都是STRING结构 - 从链表两端推入或者弹出元素
- 根据偏移量修剪链表
- 读取单个或者多个元素
- 根据值查找或者移除元素
- 可以把LIST理解为数组,基本上数组支持的操作,LIST都支持
SET 无序且不重复的STRING类型数据集合 - 添加,获取,删除单个元素
- 检查元素是否位于集合中
- 集合之间的交并差计算
- 随机获取一个元素
HSAH 包含键值对的无序集合,其中键和值都必须是STRING结构 - 添加、获取、删除单个键值对
- 获取所有键值对
ZSET 可以理解为有序HASH数据结构,只不过键的值必须是数值类型,顺序由值的大小决定 - 添加、获取、删除单个键值对
- 根据值的范围来获取元素

适用场景

参考