Redis安装及使用

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker.
根据Redis官网对Redis的定义,Redis是一种键值系统,可以用来缓存或存储数据。
Redis是“Remote Dictionary Server”(远程字典服务)的缩写,提供了字符串(string),列表(list),哈希(hash),集合(set)和有序集合(sorted set)等5种数据结构,这些数据结构使它成为一种便于使用的键值系统。

一、Redis安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[five@nagios-server ~]$ sudo yum install epel-release
[five@nagios-server ~]$ sudo yum install redis
Running transaction
Installing : jemalloc-3.6.0-1.el7.x86_64 1/2
Installing : redis-2.8.19-2.el7.x86_64 2/2
Verifying : redis-2.8.19-2.el7.x86_64 1/2
Verifying : jemalloc-3.6.0-1.el7.x86_64 2/2

Installed:
redis.x86_64 0:2.8.19-2.el7

Dependency Installed:
jemalloc.x86_64 0:3.6.0-1.el7

Complete!

[five@nagios-server ~]$ sudo systemctl start redis.service
[five@nagios-server ~]$ systemctl status redis.service
redis.service - Redis persistent key-value database
Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled)
Drop-In: /etc/systemd/system/redis.service.d
└─limit.conf
Active: active (running) since Sun 2016-04-10 18:25:56 EDT; 7s ago
Main PID: 4299 (redis-server)
CGroup: /system.slice/redis.service
└─4299 /usr/bin/redis-server 127.0.0.1:6379

# 测试Redis连接
[five@nagios-server ~]$ redis-cli ping
PONG

[five@nagios-server ~]$ redis-server --version
Redis server v=2.8.19 sha=00000000:0 malloc=jemalloc-3.6.0 bits=64 build=c0359e7aa3798aa2

通过epel源安装的redis版本为2.8.19, 目前官网最新版本为3.0.7, 需要最新版的请下载源码编译安装。

二、Redis使用

安装redis后,提供的命令行工具:

1
2
[five@nagios-server ~]$ redis-
redis-benchmark redis-check-aof redis-check-dump redis-cli redis-sentinel redis-server redis-shutdown

redis客户端: redis-cli

redis-cli: 是默认的redis客户端,可用来连接redis服务器

1
2
3
4
5
6
7
[five@nagios-server ~]$ redis-cli 
127.0.0.1:6379> ping
PONG
等同于:
[five@nagios-server ~]$ redis-cli -h 127.0.0.1 -p 6379 -a "mypass"
127.0.0.1:6379> ping
PONG

redis配置文件: redis.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[five@nagios-server ~]$ ll /etc/redis.conf 
-rw-r--r--. 1 redis root 36180 Mar 31 2015 /etc/redis.conf

# 查看所有配置项
[five@nagios-server ~]$ redis-cli
127.0.0.1:6379> CONFIG GET *
1) "dbfilename"
2) "dump.rdb"
3) "requirepass"
4) ""
5) "masterauth"
6) ""
7) "unixsocket"
8) ""
9) "logfile"
10) "/var/log/redis/redis.log"
11) "pidfile"
12) "/var/run/redis/redis.pid"

# 获取特定配置项
127.0.0.1:6379> CONFIG GET bind
1) "bind"
2) "127.0.0.1"
127.0.0.1:6379> CONFIG GET loglevel
1) "loglevel"
2) "notice"

# 修改配置项
可以直接修改redis.conf,也可以通过CONFIG SET命令:
redis 127.0.0.1:6379> CONFIG SET loglevel "notice"
OK
redis 127.0.0.1:6379> CONFIG GET loglevel

1) "loglevel"
2) "notice"

Redis数据类型

Redis不是单纯的key-values存储结构,而是一种支持不同类型数据结构values的服务器(data structures server, supporting different kind of values).
也就是说不仅可存储字符串类型的value值, 也支持更复杂数据类型的value. Redis支持的数据类型有:

1
2
3
4
5
6
7
Binary-safe strings.
Lists: collections of string elements sorted according to the order of insertion. They are basically linked lists.
Sets: collections of unique, unsorted string elements.
Sorted sets, similar to Sets but where every string element is associated to a floating number value, called score. The elements are always taken sorted by their score, so unlike Sets it is possible to retrieve a range of elements (for example you may ask: give me the top 10, or the bottom 10).
Hashes, which are maps composed of fields associated with values. Both the field and the value are strings. This is very similar to Ruby or Python hashes.
Bit arrays (or simply bitmaps): it is possible, using special commands, to handle String values like an array of bits: you can set and clear individual bits, count all the bits set to 1, find the first set or unset bit, and so forth.
HyperLogLogs: this is a probabilistic data structure which is used in order to estimate the cardinality of a set. Don't be scared, it is simpler than it seems... See later in the HyperLogLog section of this tutorial.

  • Redis Keys: Redis keys是二进制安全binary safe的,可以是简单字符串, JPEP文件内容, 甚至是为空。
    • 过长的keys不是好主意: 浪费内存, 不利搜索.
    • 过短的keys也不是好主意: 适当增加分隔符来提高可读性,但要平衡内存利用率.
    • 尝试具有可读性的keys.
    • key的最大限度为512MB.
  • Redis Strings:
    • 作为Memcached的唯一数据类型,Redis是默认支持的。GETSET命令进行读写操作。
    • 字符串最大存储512MB字节长度的内容。
    • INC命令将String转换为int后自增,同类型的命令还有INCRBY, DECR, DECRBY
    • GETSET: 将key设置新的value值,但仍返回旧的value值。
    • MSET, MGET: 在一条命令中进行多个key的设置和读取。
    • EXISTS: 判断key是否存在
    • DEL: 删除key及其对应的value值
    • Redis expires: 设定key的有效期,可以在指定时间后key过期并自动删除
    • EXPIRE, PERSIST: 设定期限和持久化key,二者是互为逆操作。
    • TTL: 查看key存活的生存周期。PEXPIRE, PTTL: 设定和查看过期key的生存时间。
  • Redis Lists: Redis中Lists是基于链表实现的,在列表首尾增加元素的时间为常数级的。弊端:当根据索引读取元素时速率较慢,这种场景下可采用后面介绍的sets结构。

    • LPUSH: 向列表头部插入数据(列表的最左侧left)
    • RPUSH: 向列表尾部插入数据(列表最右侧right)
    • LRANGE: 列举列表范围内的所有元素(LRANGE listname 0 -1: 遍历所有范围,-1表示最后一个元素, -2表示倒数第二个元素)
    • LPOP: 弹出列表中首个元素, RPOP: 弹出末尾元素。Redis列表支持栈的Push/Pop操作。
    • Lists典型应用:用户最新更新; 多进程的生产者消费者模式下,将条目加入Lists供消费者读取, Redis有特别的命令使得这一操作安全、高效.(Twitter最新推功能就是利用Redis Lists)
    • Capped lists: 很多时候我们只关心最新的N条, LTRIM提供特定范围的裁剪(类似于LRANGE,但只保留范围内元素,其他元素删除)
    • 阻塞式操作: 为了避免消费者生产者模型下对List不断等待、判断是否为空的无效操作, Redis通过BLPOP, BRPOP在列表为空时阻塞进程, 直到新的元素加入列表。
    • 安全的队列或循环队列可采用RPOPLPUSH或者阻塞式的BRPOPLPUSH.
    • 自动删除与创建: Redis自动删除空的多元素类数据类型, 或在插入新数据前自动创建. 原因:
      1)插入前如果为空,自动创建
      2) 复合类型数据元素为空时,自动销毁
      3) 只读操作values为空的key和删除key的返回值是一样的
  • Redis Hashes

    • HMSET: 设置hash多个字段
    • HGET: 获取hash中的一个字段
    • HMGET: 获取hash中的多个字段,返回数组
    • 注意: 小的hash结构(包含小数据量的元素)通过特殊方式的内存编码具有很高的访问效率。
      1
      2
      3
      4
      5
      6
      127.0.0.1:6379> hmset hashtest name fivezh age 28
      OK
      127.0.0.1:6379> hget hashtest name
      "fivezh"
      127.0.0.1:6379> hget hashtest age
      "28"
  • Redis Sets: 集合, 字符串的无序集合

    • SADD向集合中添加新元素, SMEMBERS获取集合中所有元素, SISMEMBER判断元素是否存在
    • 集合元素是无序的
    • 集合其他操作:判断元素是否存在, 插入, 交集, 差集等等
    • Set应用:不同ID文章具有的标签,将标签作为Set的key, 包含所有该标签对应的文章ID
    • SINTER: 返回不同集合的交集
    • SPOP: 取出集合中的任一元素
    • SUNIONSTORE: 多个key的交集并存储在集合中,返回集合中元素个数
    • SCAR: 返回集合的基数(集合中元素数量)
    • Redis 有序集合: Hash与Set的合体: Set的元素不相同的特点, 通过每个元素关联的score来进行元素的排序(hash类似的结构)
    • ZADD: 有序集合中插入元素(插入元素的同时,设定每个元素的score值)
    • ZRANGE: 获取有序集合中指定范围的元素
    • ZREVRANGE: 获取有序集合中元素的逆序, 与ZRANGE逆序
    • ZRANGE或ZREVRANGE调用时增加WITHSCORE, 将输出相应的分值
    • 区间操作:ZRANGEBYSCORE获取评分在区间范围内的元素,ZREMRANGEBYSCORE删除区间内的元素(返回操作的元素个数)
    • ZREVRANK: 返回由高到低排序中元素的排名, ZRANK: 返回升序时的该元素的排名
  • Bitmaps:

    • Bitmaps其实就是基于位操作的字符串类型。
    • 位操作可分为两种类型:1)常数时间的单个位操作,如设置某位为1或0, 获取其值, 2)一组位操作.
    • SETBIT, GETBIT: 前者为设置key某一位的值,后者为获取。未设置值得位在Redis中默认为0.
    • BITOP: 位操作,包括AND, OR, XOR, NOT等位操作.
    • BITCOUNT: 统计key中为1的位的个数.

      1
      2
      3
      4
      5
      6
      > setbit key 0 1
      (integer) 0
      > setbit key 100 1
      (integer) 0
      > bitcount key
      (integer) 2
    • BITPOS: 找出key中首个1或0的位置.

    • Bitmaps的典型应用:1)各种实时分析系统 2)存储和对象ID相关的空间和性能高效的布尔信息
  • HyperLogLogs: 一种数据结构,用于统计不同项元素的频次, 简称HLLs

    • HLL使用少量内存实现了对频次的统计(误差范围1%)
    • PFADD, PFCOUNT用于增加和统计该数据结构中的元素
    • 类似于Set的SADD和SCARD命令分别用于添加和统计集合元素数。
      1
      2
      3
      4
      > pfadd hll a b c d
      (integer) 1
      > pfcount hll
      (integer) 4

更多阅读:

Redis命令

Redis发布/订阅模型

Redis增量迭代

参考文献

  1. 初学Redis(1)——认识Redis
  2. Redis 教程
  3. Redis Commands
  4. Redis 命令参考