redis-数据库 键过期如何删除

参考:http://origin.redisbook.com/internal/db.html

Redis 有四个命令可以设置键的生存时间(可以存活多久)和过期时间(什么时候到期):

  • EXPIRE 以秒为单位设置键的生存时间;
  • PEXPIRE 以毫秒为单位设置键的生存时间;
  • EXPIREAT 以秒为单位,设置键的过期 UNIX 时间戳;
  • PEXPIREAT 以毫秒为单位,设置键的过期 UNIX 时间戳。

redis 通过 EXPIRE 、 PEXPIRE 、 EXPIREAT 和 PEXPIREAT 四个命令, 客户端可以给某个存在的键设置过期时间, 当键的过期时间到达时, 键就不再可用。

在数据库中, 所有键的过期时间都被保存在 redisDb 结构的 expires 字典里:

typedef struct redisDb {

    // ...

    dict *expires; // ... } redisDb; 

expires 字典的键是一个指向 dict 字典(键空间)里某个键的指针, 而字典的值则是键所指向的数据库键的到期时间, 这个值以 long long 类型表示。

下图展示了一个含有三个键的数据库,其中 number 和 book 两个键带有过期时间:

digraph db_with_expire_time {

    rankdir = LR;

    node [shape = record, style = filled];

    edge [style = bold];

    // node

    redisDb [label = "redisDb | id |<dict> dict |<expires> expires | ...", fillcolor = "#A8E270"];

    // dict

    dict [label = "<head>dict\n(key space) |<number>StringObject\n \"number\" | NULL |<book>StringObject\n \"book\" |<message>StringObject\n \"message\"", fillcolor = "#95BBE3"];

    number [label = "<head>ListObject | { 123 | 456 | 789 }", fillcolor = "#FADCAD"];

    book [label = "<head>HashObject |<name>StringObject\n \"name\" |<author>StringObject\n \"author\" |<publisher>StringObject\n \"publisher\"", fillcolor = "#F2F2F2"];

    book_name [label = "<head>StringObject | \"Mastering C++ in 21 days\""];
    book_author [label = "<head>StringObject | \"Someone\""];
    book_publisher [label = "<head>StringObject | \"Oh-Really? Publisher\""];

    message [label = "<head>StringObject | \"hello moto\""];

    // dict edge

    redisDb:dict -> dict:head;

    dict:number -> number:head;
    dict:book -> book:head;
    dict:message -> message:head;

    book:name -> book_name:head;
    book:author -> book_author:head;
    book:publisher -> book_publisher:head;

    // expires

    expires [label = "<head>dict |<number>StringObject\n \"number\" | NULL |<book>StringObject\n \"book\" | NULL ", fillcolor = "#95BBE3"];

    expire_of_number [label = "<head>long long | 1360454400000 "];

    expire_of_book [label = "<head>long long | 1360800000000 "];

    // expires edge

    redisDb:expires -> expires:head;

    expires:number -> expire_of_number:head;
    expires:book -> expire_of_book:head;

}

为了展示的方便, 图中重复出现了两次 number 键和 book 键。 在实际中, 键空间字典的键和过期时间字典的键都指向同一个字符串对象, 所以不会浪费任何空间。

 

1、如何判断键过期了?

通过 expires 字典, 可以用以下步骤检查某个键是否过期:

a、检查键是否存在于 expires 字典:如果存在,那么取出键的过期时间;

b、检查当前 UNIX 时间戳是否大于键的过期时间:如果是的话,那么键已经过期;否则,键未过期。

2、过期键 什么时候删除?

a、定时删除:在设置键的过期时间时,创建一个定时事件,当过期时间到达时,由事件处理器自动执行键的删除操作。

b、惰性删除:放任键过期不管,但是在每次从 dict 字典中取出键值时,要检查键是否过期,如果过期的话,就删除它,并返回空;如果没过期,就返回键值。

c、定期删除:每隔一段时间,对 expires 字典进行检查,删除里面的过期键。

猜你喜欢

转载自www.cnblogs.com/albert32/p/13393012.html
今日推荐