RedisREmote DIctionary Server)是一个数据结构服务端(Data structure server)。其本质上就是一个 Key/Value 数据库,具有开源(Open-source)、基于网络(Networked)且可以采用不同的持久化策略(Optional durability)来保存键值等特点。

它的值可以是 string(字符串)、list(列表)、sets(集合)或者是 ordered sets(被排序的集合),所有的数据类型都具有 push/popadd/remove、执行服务端的并集、交集、两个 sets 集中的差别等等操作,这些操作都是具有原子性的。

Redis 还支持各种不同的排序。

它是当今最负盛名的键值(Key-Value)存储引擎。

According to the monthly ranking by DB-Engines.com, Redis is the most popular key-value store.
—— http://en.wikipedia.org/wiki/Redis

相比较于 Memcached (另一个广泛使用的 NoSQL 型数据库),它的数据可以持久化的保存在磁盘上,解决了服务重启后数据丢失的问题。

本手册内容为 http://redis.io/ (Redis 官方网站)的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez (网络 ID,其实姓名为 Salvatore Sanfilippo)为开源社区作出的贡献,本手册保证最新、最准、最全以表示对其的敬意。

欢迎留言纠错、提示更新或支持。如果能 收藏 或 分享 本手册,则是对译者最大的支持,感谢!

以下为本手册所有内容的分类及索引。

    • append only file(aof)  全持久化模式
    • <REDIS_FILE>                    Redis 解压目录
    • <REDIS_HOME>                    Redis 安装目录
  • // Delete a key
    DEL key [key ...]
    // Return a serialized version of the value stored at the specified key
    DUMP key
    // Determine if a key exists
    EXISTS key
    // Set a key's time to live in seconds
    EXPIRE key seconds
    // Set the expiration for a key as a UNIX timestamp
    EXPIREAT key timestamp
    // Find all keys matching the given pattern
    KEYS pattern
    // Atomically transfer a key from a Redis instance to another one
    MIGRATE host port key destination-db timeout [COPY] [REPLACE]
    // Move a key to another database
    MOVE key db
    // Inspect the internals of Redis objects
    OBJECT subcommand [arguments [arguments ...]]
    // Remove the expiration from a key
    PERSIST key
    // Set a key's time to live in milliseconds
    PEXPIRE key milliseconds
    // Set the expiration for a key as a UNIX timestamp specified in milliseconds
    PEXPIREAT key milliseconds-timestamp
    // Get the time to live for a key in milliseconds
    PTTL key
    // Return a random key from the keyspace
    RANDOMKEY
    // Rename a key
    RENAME key newkey
    // Rename a key, only if the new key does not exist
    RENAMENX key newkey
    // Create a key using the provided serialized value, previously obtained using DUMP
    RESTORE key ttl serialized-value
    // Get the time to live for a key
    TTL key
    // Determine the type stored at key
    TYPE key
    // Incrementally iterate the keys space
    SCAN cursor [MATCH pattern] [COUNT count]
    // Sort the elements in a list, set or sorted set
    SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]

    详细

  • // Append a value to a key
    APPEND key value
    // Count set bits in a string
    BITCOUNT key [start end]
    // Perform bitwise operations between strings
    BITOP operation destkey key [key ...]
    // Find first bit set or clear in a string
    BITPOS key bit [start] [end]
    // Decrement the integer value of a key by one
    DECR key
    // Decrement the integer value of a key by the given number
    DECRBY key decrement
    // Get the value of a key
    GET key
    // Returns the bit value at offset in the string value stored at key
    GETBIT key offset
    // Get a substring of the string stored at a key
    GETRANGE key start end
    // Set the string value of a key and return its old value
    GETSET key value
    // Increment the integer value of a key by one
    INCR key
    // Increment the integer value of a key by the given amount
    INCRBY key increment
    // Increment the float value of a key by the given amount
    INCRBYFLOAT key increment
    // Get the values of all the given keys
    MGET key [key ...]
    // Set multiple keys to multiple values
    MSET key value [key value ...]
    // Set multiple keys to multiple values, only if none of the keys exist
    MSETNX key value [key value ...]
    // Set the value and expiration in milliseconds of a key
    PSETEX key milliseconds value
    // Set the string value of a key
    SET key value [EX seconds] [PX milliseconds] [NX|XX]
    // Sets or clears the bit at offset in the string value stored at key
    SETBIT key offset value
    // Set the value and expiration of a key
    SETEX key seconds value
    // Set the value of a key, only if the key does not exist
    SETNX key value
    // Overwrite part of a string at key starting at the specified offset
    SETRANGE key offset value
    // Get the length of the value stored in a key
    STRLEN key

    详细

  • // AddDelete one or more hash fields
    HDEL key field [field ...]
    // AddDetermine if a hash field exists
    HEXISTS key field
    // AddGet the value of a hash field
    HGET key field
    // AddGet all the fields and values in a hash
    HGETALL key
    // AddIncrement the integer value of a hash field by the given number
    HINCRBY key field increment
    // AddIncrement the float value of a hash field by the given amount
    HINCRBYFLOAT key field increment
    // AddGet all the fields in a hash
    HKEYS key
    // AddGet the number of fields in a hash
    HLEN key
    // AddGet the values of all the given hash fields
    HMGET key field [field ...]
    // AddSet multiple hash fields to multiple values
    HMSET key field value [field value ...]
    // AddIncrementally iterate hash fields and associated values
    HSCAN key cursor [MATCH pattern] [COUNT count]
    // AddSet the string value of a hash field
    HSET key field value
    // AddSet the value of a hash field, only if the field does not exist
    HSETNX key field value
    // AddGet all the values in a hash
    HVALS key

    详细

  • // Remove and get the first element in a list, or block until one is available
    BLPOP key [key ...] timeout
    // Remove and get the last element in a list, or block until one is available
    BRPOP key [key ...] timeout
    // Pop a value from a list, push it to another list and return it; or block until one is available
    BRPOPLPUSH source destination timeout
    // Get an element from a list by its index
    LINDEX key index
    // Insert an element before or after another element in a list
    LINSERT key BEFORE|AFTER pivot value
    // Get the length of a list
    LLEN key
    // Remove and get the first element in a list
    LPOP key
    // Prepend one or multiple values to a list
    LPUSH key value [value ...]
    // Prepend a value to a list, only if the list exists
    LPUSHX key value
    // Get a range of elements from a list
    LRANGE key start stop
    // Remove elements from a list
    LREM key count value
    // Set the value of an element in a list by its index
    LSET key index value
    // Trim a list to the specified range
    LTRIM key start stop
    // Remove and get the last element in a list
    RPOP key
    // Remove the last element in a list, append it to another list and return it
    RPOPLPUSH source destination
    // Append one or multiple values to a list
    RPUSH key value [value ...]
    // Append a value to a list, only if the list exists
    RPUSHX key value
    

    详细

  • // Add one or more members to a set
    SADD key member [member ...]
    // Get the number of members in a set
    SCARD key
    // Subtract multiple sets
    SDIFF key [key ...]
    // Subtract multiple sets and store the resulting set in a key
    SDIFFSTORE destination key [key ...]
    // Intersect multiple sets
    SINTER key [key ...]
    // Intersect multiple sets and store the resulting set in a key
    SINTERSTORE destination key [key ...]
    // Determine if a given value is a member of a set
    SISMEMBER key member
    // Get all the members in a set
    SMEMBERS key
    // Move a member from one set to another
    SMOVE source destination member
    // Remove and return a random member from a set
    SPOP key
    // Get one or multiple random members from a set
    SRANDMEMBER key [count]
    // Remove one or more members from a set
    SREM key member [member ...]
    // Add multiple sets
    SUNION key [key ...]
    // Add multiple sets and store the resulting set in a key
    SUNIONSTORE destination key [key ...]
    // Incrementally iterate Set elements
    SSCAN key cursor [MATCH pattern] [COUNT count]
    

    详细

  • // Add one or more members to a sorted set, or update its score if it already exists
    ZADD key score member [score member ...]
    // Get the number of members in a sorted set
    ZCARD key
    // Count the members in a sorted set with scores within the given values
    ZCOUNT key min max
    // Increment the score of a member in a sorted set
    ZINCRBY key increment member
    // Intersect multiple sorted sets and store the resulting sorted set in a new key
    ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
    // Count the number of members in a sorted set between a given lexicographical range
    ZLEXCOUNT key min max
    // Return a range of members in a sorted set, by index
    ZRANGE key start stop [WITHSCORES]
    // Return a range of members in a sorted set, by lexicographical range
    ZRANGEBYLEX key min max [LIMIT offset count]
    // Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.
    ZREVRANGEBYLEX key max min [LIMIT offset count]
    // Return a range of members in a sorted set, by score
    ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
    // Determine the index of a member in a sorted set
    ZRANK key member
    // Remove one or more members from a sorted set
    ZREM key member [member ...]
    // Remove all members in a sorted set between the given lexicographical range
    ZREMRANGEBYLEX key min max
    // Remove all members in a sorted set within the given indexes
    ZREMRANGEBYRANK key start stop
    // Remove all members in a sorted set within the given scores
    ZREMRANGEBYSCORE key min max
    // Return a range of members in a sorted set, by index, with scores ordered from high to low
    ZREVRANGE key start stop [WITHSCORES]
    // Return a range of members in a sorted set, by score, with scores ordered from high to low
    ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
    // Determine the index of a member in a sorted set, with scores ordered from high to low
    ZREVRANK key member
    // Get the score associated with the given member in a sorted set
    ZSCORE key member
    // Add multiple sorted sets and store the resulting sorted set in a new key
    ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
    // Incrementally iterate sorted sets elements and associated scores
    ZSCAN key cursor [MATCH pattern] [COUNT count]

    详细

  • // Adds the specified elements to the specified HyperLogLog.
    PFADD key element [element ...]
    // Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
    PFCOUNT key [key ...]
    // Merge N different HyperLogLogs into a single one.
    PFMERGE destkey sourcekey [sourcekey ...]
    

    详细

  • // Listen for messages published to channels matching the given patterns
    PSUBSCRIBE pattern [pattern ...]
    // Inspect the state of the Pub/Sub subsystem
    PUBSUB subcommand [argument [argument ...]]
    // Post a message to a channel
    PUBLISH channel message
    // Stop listening for messages posted to channels matching the given patterns
    PUNSUBSCRIBE [pattern [pattern ...]]
    // Listen for messages published to the given channels
    SUBSCRIBE channel [channel ...]
    // Stop listening for messages posted to the given channels
    UNSUBSCRIBE [channel [channel ...]]

    详细

  • // Discard all commands issued after MULTI
    DISCARD
    // Execute all commands issued after MULTI
    EXEC
    // Mark the start of a transaction block
    MULTI
    // Forget about all watched keys
    UNWATCH
    // Watch the given keys to determine execution of the MULTI/EXEC block
    WATCH key [key ...]

    详细

  • // Execute a Lua script server side
    EVAL script numkeys key [key ...] arg [arg ...]
    // Execute a Lua script server side
    EVALSHA sha1 numkeys key [key ...] arg [arg ...]
    // Check existence of scripts in the script cache.
    SCRIPT EXISTS script [script ...]
    // Remove all the scripts from the script cache.
    SCRIPT FLUSH
    // Kill the script currently in execution.
    SCRIPT KILL
    // Load the specified Lua script into the script cache.
    SCRIPT LOAD script

    详细

  • // Authenticate to the server
    AUTH password
    // Echo the given string
    ECHO message
    // Ping the server
    PING
    // Close the connection
    QUIT
    // Change the selecte
    SELECT index
    

    详细

  • // Asynchronously rewrite the append-only file
    BGREWRITEAOF
    // Asynchronously save the dataset to disk
    BGSAVE
    // Kill the connection of a client
    CLIENT KILL [ip:port] [ID client-id] [TYPE normal|slave|pubsub] [ADDR ip:port] [SKIPME yes/no]
    // Get the list of client connections
    CLIENT LIST
    // Get the current connection name
    CLIENT GETNAME
    // Stop processing commands from clients for some time
    CLIENT PAUSE timeout
    // Set the current connection name
    CLIENT SETNAME connection-name
    // Get array of Cluster slot to node mappings
    CLUSTER SLOTS
    // Get array of Redis command details
    COMMAND
    // Get total number of Redis commands
    COMMAND COUNT
    // Extract keys given a full Redis command
    COMMAND GETKEYS
    // Get array of specific Redis command details
    COMMAND INFO command-name [command-name ...]
    // Get the value of a configuration parameter
    CONFIG GET parameter
    // Rewrite the configuration file with the in memory configuration
    CONFIG REWRITE
    // Set a configuration parameter to the given value
    CONFIG SET parameter value
    // Reset the stats returned by INFO
    CONFIG RESETSTAT
    // Return the number of keys in the selected database
    DBSIZE
    // Get debugging information about a key
    DEBUG OBJECT key
    // Make the server crash
    DEBUG SEGFAULT
    // Remove all keys from all databases
    FLUSHALL
    // Remove all keys from the current database
    FLUSHDB
    // Get information and statistics about the server
    INFO [section]
    // Get the UNIX time stamp of the last successful save to disk
    LASTSAVE
    // Listen for all requests received by the server in real time
    MONITOR
    // Return the role of the instance in the context of replication
    ROLE
    // Synchronously save the dataset to disk
    SAVE
    // Synchronously save the dataset to disk and then shut down the server
    SHUTDOWN [NOSAVE] [SAVE]
    // Make the server a slave of another instance, or promote it as master
    SLAVEOF host port
    // Manages the Redis slow queries log
    SLOWLOG subcommand [argument]
    // Internal command used for replication
    SYNC
    // Return the current server time
    TIME

    详细

  • (以 2.6 版本 为例)


    根目录下:

    redis.conf 默认配置文件。

    Src 目录:

    make 命令执行完成后,会在 src 目录下生成 5 个可执行文件,分别是 redis-serverredis-cliredis-benchmarkredis-check-aofredis-check-dump

  • 编译 Redis 的要求如下:

    必须保证有 50G 以上的临时磁盘自由空间。Redis 安装完毕后会占据 10MB 左右的空间,实际磁盘需求会因编译设置和是否安装第三方模块而有所不同。

  • 进入 redis 解压目录,执行如下命令编译 Redis

    cd <REDIS_FILE>
    make test  
    make prefix=<REDIS_HOME> install

    Redis 编译失败怎么办

    • 检查配置参数是否正确。
    • 当前用户对 --prefix 目录是否有权限。
    • 系统是否安装 gcc 编译工具。
    • 如果编译失败再次编译出现故障,请删除 Redis 的源代码目录,再次解压 Redis,新编译。
  • 进入当前用户主目录后执行:

    vi .bash_profile

    然后写入:

    PATH=$PATH:.:$<REDIS_HOME>/bin:$PATH

    保存后执行如下命令:

     . .bash_profile 

    退出终端,重新登录后查看环境变量是否生效。

  • 启动 Redis 服务器

    命令:

    cd <REDIS_HOME>/bin
    redis-server conf/redis.conf

    注:此命令仅有一个启动参数,指定 <REDIS_FILE> 目录下的配置文件,不加参数执行默认配置。

    测试启动:

    redis-cli ping

    返回 PONG,启动成功。

    查看端口是否被占用:

    netstat –ntlp |grep 6379  

    查看 redis 进程:

    ps –ef |grep redis

    停止 Redis

    关闭服务:

    redis-cli shutdown

    如果非默认端口,可指定端口:

    redis-cli -p 6380 shutdown

    连接 Redis

    两种连接方式:

    1. window 方式:tentel 主机 IP 端口号(默认为 127.0.0.1:6379
    2. linux 客户端方式:redis-cli 主机 IP 端口号(默认为 127.0.0.1 6379


    redis-cli –h 127.0.0.1 –p 6379
  • 如果 Redis 已经安装过,请先备份原 Redis 的所有配置文件,即 <REDIS_HOME> 目录下的所有文件。