Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

You can run atomic operations on these types, like appending to a string; incrementing the value in a hash; pushing an element to a list; computing set intersection, union and difference; or getting the member with highest ranking in a sorted set.

In order to achieve its outstanding performance, Redis works with an in-memory dataset. Depending on your use case, you can persist it either by dumping the dataset to disk every once in a while, or by appending each command to a log. Persistence can be optionally disabled, if you just need a feature-rich, networked, in-memory cache.

Redis also supports trivial-to-setup master-slave asynchronous replication, with very fast non-blocking first synchronization, auto-reconnection with partial resynchronization on net split.

Other features include:

  • Transactions
  • Pub/Sub
  • Lua scripting
  • Keys with a limited time-to-live
  • LRU eviction of keys
  • Automatic failover

You can use Redis from most programming languages out there.

Redis is written in ANSI C and works in most POSIX systems like Linux, *BSD, OS X without external dependencies. Linux and OS X are the two operating systems where Redis is developed and more tested, and we recommend using Linux for deploying. Redis may work in Solaris-derived systems like SmartOS, but the support is best effort. There is no official support for Windows builds, but Microsoft develops and maintains a Win-64 port of Redis.

reids是用c语言编写的,官方支持posix(linux,mac)
微软的同学们对win64版本进行了开发和维护
以下是对redis的一些源码实现的简单整理,大部分为对《Redis设计与实现》一书中的一些摘要与理解。

字符串

Redis数据结构中没有使用c语言传统的字符串,而是自己实现了一个名为SDS(simple dynamic string)的抽象类型,但在一些不需要对字符串进行修改的地方如日志打印等使用了c传统的字符串,


sds.png

上图 是sds的结构图,可以对sds分配一个定额的空间,其中,

  • free表示尚未使用的空间,
  • len表示以及保存的字符串的长度,
  • buf用来保存字符串(仍像c语言中一样以\0结尾,但\0不记录在len中)。

SDS的一些特点

  • 常数复杂度获取字符串长度
  • 杜绝缓冲区溢出
  • 减少修改字符串时带来的内存重新分配次数

为了实现上述特点,sds实现了两种优化策略

空间预分配

额外分配的未使用空间数量分配规则:

  • 对sds进行修改之后要进行如下分配
  • 如果修改之后sds的长度(len)小于1MB,程序会分配和len属性同样大小的未使用空间,即令free=len。 总长度(free + len + 1byte)
  • 如果修改之后sds的长度大于1MB,会分配1MB的未使用空间,free= 1MB。总长度(len + 1MB + 1byte)

惰性空间释放

用于优化sds字符串缩短操作,在字符串缩短时,将内存放入free中,不会回收。
sds也提供了api,可以在有需要时,释放sds未使用的空间,所以不必担心这种释放方式会浪费内存。

二进制安全

在c语言中的字符串必须符合某种编码,只能保存一些文本数据,如果存入一些二进制媒体数据,会出现误判。
sds是二进制安全 的,不会对数据做任何的过滤,限制

兼容部分c字符串函数

由于sds是与c一样也使用\0表示结束,所以可以兼容部分string.h的api

你可能感兴趣的:(Redis)