一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|數據庫技術|

服務器之家 - 數據庫 - Redis - 關于redis Key淘汰策略的實現方法

關于redis Key淘汰策略的實現方法

2019-11-05 12:10jingxian Redis

下面小編就為大家?guī)硪黄P于redis Key淘汰策略的實現方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

1 配置文件中的最大內存刪除策略

在redis的配置文件中,可以設置redis內存使用的最大值,當redis使用內存達到最大值時(如何知道已達到最大值?),redis會根據配置文件中的策略選取要刪除的key,并刪除這些key-value的值。若根據配置的策略,沒有符合策略的key,也就是說內存已經容不下新的key-value了,但此時有不能刪除key,那么這時候寫的話,將會出現寫錯誤。


1.1 最大內存參數設置

若maxmemory參數設置為0,則分兩種情況:

*在64位系統(tǒng)上,表示沒有限制。
*在32為系統(tǒng)上,是3G,redis官方文檔的說法是,32位系統(tǒng)最大內存是4G,預留1G給系統(tǒng)。而且策略會自動設置為noeviction。

也就是說在32位系統(tǒng)上,若maxmemory設置為0,則默認是3G,當到達3G,再往reidis中寫入時,則會報錯。


1.2 到達最大內存時的幾種刪除key的策略

*  volatile-lru -> remove the key with an expire set using an LRU algorithm
    按照LRU算法(最少最近沒使用)來選取,并刪除已經設置了expire時間的key。
*  allkeys-lru -> remove any key accordingly to the LRU algorithm
    根據LRU算法,刪除任意的key。不論這個key是否設置了expire時間。
*  volatile-random -> remove a random key with an expire set
    隨機刪除一個設置了expire時間的key。
*  allkeys-random -> remove a random key, any key
    隨機刪除任意一個key,不論這個key是否設置了expire時間。
*  volatile-ttl -> remove the key with the nearest expire time (minor TTL)
    刪除具有最近終止時間值(TTL)的key。
*  noeviction -> don't expire at all, just return an error on write operations
    若沒有設置終止時間,返回一個錯誤。


1.3 配置內存最大值策略

以下這些命令的默認策略是:volatile-lru

 # At the date of writing this commands are: set setnx setex append
 # incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
 # sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
 # zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
 # getset mset msetnx exec sort
 #
 # The default is:
 # maxmemory-policy volatile-lru


1.4 配置要刪除key的檢測樣本個數

maxmemory-samples

由于LRU和最小TTL算法都是不是精確的算法。因此你可以選擇要檢測樣本的個數。例如,默認情況下redis將會檢查3個key,并從這3個key中選取一個最近沒有使用的key。當然你可以修改檢查樣本的個數的值。

要修改這個值,可以通過在配置文件中設置參數:

maxmemory-samples 3

2 實現

這幾種刪除策略的實現都是在函數 freeMemoryIfNeeded(void) 中完成的。下面具體講解每種策略是如何實現的。

2.1 什么時候去刪除key-value

當設置了maxmemory-policy策略后,什么時候會去刪除key呢?

實際上,當設置了maxmemory參數后,在處理每個命令的時候都會根據maxmemory-policy去刪除對應的key值。

代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 處理客戶端的每個命令,都會調用這個函數
int processCommand(redisClient *c) {
  ... ...
  /* Handle the maxmemory directive.
   *
   * First we try to free some memory if possible (if there are volatile
   * keys in the dataset). If there are not the only thing we can do
   * is returning an error. */
  // 以上意思是:若存在可以刪除的key,就釋放一些內存,若不存在,給客戶端返回一個錯誤。
  if (server.maxmemory) {               // 若maxmemory不為0,則調用以下函數,釋放其中一些key
    int retval = freeMemoryIfNeeded();   // 根據配置策略刪除key
    if ((c->cmd->flags & REDIS_CMD_DENYOOM) && retval == REDIS_ERR) {  // 若出錯,就終止處理命令,把錯誤返回給客戶端
      flagTransaction(c);
      addReply(c, shared.oomerr);
      return REDIS_OK;
    }
  }
  ... ...
}

 


實戰(zhàn)1:若沒有設置maxmemory變量,即使設置了maxmemory-policy,也不會起作用。

實戰(zhàn)2:若沒有設置maxmemory變量,在處理命令時將不會調用釋放策略,會加速命令的處理過程。

2.2 刪除key的總體流程

當內存達到最大值時需要按策略刪除老的key,所有的刪除操作和刪除策略的實現都是在函數freeMemoryIfNeeded()中實現的。

在執(zhí)行刪除策略之前,先要選取db和查找key。

總體步驟如下:

?
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
int freeMemoryIfNeeded(void) {
  size_t mem_used, mem_tofree, mem_freed;
  int slaves = listLength(server.slaves);
  mstime_t latency;
 
 
  /* Remove the size of slaves output buffers and AOF buffer from the
   * count of used memory. */
  mem_used = zmalloc_used_memory();
  if (slaves) {
    listIter li;
    listNode *ln;
 
 
    listRewind(server.slaves,&li);
    while((ln = listNext(&li))) {
      redisClient *slave = listNodeValue(ln);
      unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave);
      if (obuf_bytes > mem_used)
        mem_used = 0;
      else
        mem_used -= obuf_bytes;
    }
  }
  if (server.aof_state != REDIS_AOF_OFF) {
    mem_used -= sdslen(server.aof_buf);
    mem_used -= aofRewriteBufferSize();
  }
 
 
  /* Check if we are over the memory limit. */
  // 檢查目前系統(tǒng)是否超過內存的限制
  if (mem_used <= server.maxmemory) return REDIS_OK;
 
 
  if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
    return REDIS_ERR; /* We need to free memory, but policy forbids. */
 
 
  /* Compute how much memory we need to free. */
  mem_tofree = mem_used - server.maxmemory;
  mem_freed = 0;
  latencyStartMonitor(latency);
  while (mem_freed < mem_tofree) {
    int j, k, keys_freed = 0;
    // 遍歷16個數據庫
 
 
    for (j = 0; j < server.dbnum; j++) {
      long bestval = 0; /* just to prevent warning */
      sds bestkey = NULL;
      struct dictEntry *de;
      redisDb *db = server.db+j;
      dict *dict;
 
 
      // 這里要注意,若是ALLKEYS_xx策略,則直接在對應庫結構的dict中查找key。
      // 若是非ALLKEYS_xx策略,也就是可能是 volatile-xxx等策略,操作的庫結構將設置成expires結構。
 
 
      if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
        server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
      {
        // 若設置了
        dict = server.db[j].dict;
      } else {
        dict = server.db[j].expires;
      }
      // 若數據庫的大小為0,說明沒有key存在,繼續(xù)在下一個數據庫中查找
      if (dictSize(dict) == 0) continue;
 
 
... ...
 
 
}

2.2 volatile-lru機制和allkeys-lru的實現

2.2.1 redis中的LRU機制

對于LRU機制,redis的官方文檔有這樣的解釋:

?
1
2
3
4
5
6
7
8
Redis LRU algorithm is not an exact implementation. This means that Redis is not able to pick the best candidate for eviction, that is, the access that was accessed the most in the past. Instead it will try to run an approximation of the LRU algorithm, by sampling a small number of keys, and evicting the one that is the best (with the oldest access time) among the sampled keys.
 
However since Redis 3.0 (that is currently in beta) the algorithm was improved to also take a pool of good candidates for eviction. This improved the performance of the algorithm, making it able to approximate more closely the behavior of a real LRU algorithm.
What is important about the Redis LRU algorithm is that you are able to tune the precision of the algorithm by changing the number of samples to check for every eviction. This parameter is controlled by the following configuration directive:
 
maxmemory-samples 5
 
The reason why Redis does not use a true LRU implementation is because it costs more memory. However the approximation is virtually equivalent for the application using Redis. The following is a graphical comparison of how the LRU approximation used by Redis compares with true LRU.

 

大意是說,redis的LRU算法不是正真意思上的LRU。而是使用另外一種方式實現的。也就意味著,redis并不能每次都選擇一個最好的key來刪除。沒有使用正真的LRU算法的原因是,它可能會消耗更多的內存。該算法和正真的LRU算法效果大概相同。

redis是在一小部分key中選擇最優(yōu)的要刪除的key。這一小部分key的個數可以指定,可以在配置文件中設置參數maxmemory-samples 。

2.2.2 LRU機制的實現

freeMemoryIfNeeded()函數,首先要計算最大空余內存和目前已經使用的內存大差值,若不夠了,就要釋放老的key-value。

若使用的是LRU策略,就會走以下代碼,先進行最優(yōu)刪除key的選擇,然后進行刪除操作:

?
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
int freeMemoryIfNeeded(void) {
  size_t mem_used, mem_tofree, mem_freed;
  int slaves = listLength(server.slaves);
  mstime_t latency;
 
 
  /* Remove the size of slaves output buffers and AOF buffer from the
   * count of used memory. */
  mem_used = zmalloc_used_memory(); // 計算目前使用的內存大小,要排除slave和AOF使用的buffer大小
  if (slaves) { //遍歷slaves鏈表,減去slave使用的內存數量
    listIter li;
    listNode *ln;
 
 
    listRewind(server.slaves,&li);
    while((ln = listNext(&li))) {
      redisClient *slave = listNodeValue(ln);
      unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave);
      if (obuf_bytes > mem_used)
        mem_used = 0;
      else
        mem_used -= obuf_bytes;
    }
  }
  if (server.aof_state != REDIS_AOF_OFF) { //減去AOF使用的內存大小
    mem_used -= sdslen(server.aof_buf);
    mem_used -= aofRewriteBufferSize();
  }
 
 
  /* Check if we are over the memory limit. */ //檢查是否達到設置的內存上限
  if (mem_used <= server.maxmemory) return REDIS_OK;
  // 不釋放內存
  if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
    return REDIS_ERR; /* We need to free memory, but policy forbids. */
 
 
  /* Compute how much memory we need to free. */ //計算要釋放的內存量
  mem_tofree = mem_used - server.maxmemory;
  mem_freed = 0;
  latencyStartMonitor(latency);
  while (mem_freed < mem_tofree) { //已經釋放的內存小于要釋放的內存量
    int j, k, keys_freed = 0;
 
 
    for (j = 0; j < server.dbnum; j++) { //遍歷所有數據庫開始釋放內存
      long bestval = 0; /* just to prevent warning */
      sds bestkey = NULL;
      struct dictEntry *de;
      redisDb *db = server.db+j;
      dict *dict;
 
 
       // 這一步要先選擇淘汰取值的數據庫的dict
      if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
        server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
      { //若maxmemory-policy的值是LRU或RANDOM時,直接在主數據庫中進行淘汰
        dict = server.db[j].dict;
      } else { // 其他策略,在已經設置了終止時間的key中間進行淘汰。
        dict = server.db[j].expires;
      }
      if (dictSize(dict) == 0) continue; //當前數據庫沒有數據跳過
 
 
      /* volatile-random and allkeys-random policy */ //若是RANDOM策略中的一個
      if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
        server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
      {
        de = dictGetRandomKey(dict);
        bestkey = dictGetKey(de);
      }
 
 
      /* volatile-lru and allkeys-lru policy */// 若刪除策略是LRU策略中的一個
      else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
        server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
      {
        // 根據配置文件中maxmemory_samples的值,決定做幾次選擇,刪除的key要從這些key中選出來。
        for (k = 0; k < server.maxmemory_samples; k++) {
          sds thiskey;
          long thisval;
          robj *o;
 
 
          // 從庫中隨機選取一個key-value結構(dictEntry類型)的節(jié)點
          de = dictGetRandomKey(dict);
          thiskey = dictGetKey(de); // // 從該節(jié)點中獲取key的字符串地址
          /* When policy is volatile-lru we need an additional lookup
           * to locate the real key, as dict is set to db->expires. */
          // 若最大內存刪除策略是volatile-lru,則需要從db中查找thiskey。
          // 若是VOLATILE-xx策略,則目前操作的庫的存儲結構是expires,此時需要從dict中找到該key
          if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
            de = dictFind(db->dict, thiskey);
          // 獲取key de的value值
          o = dictGetVal(de);
          // 查看該key的剩下的生存時間
          thisval = estimateObjectIdleTime(o);
 
 
          /* Higher idle time is better candidate for deletion */
          // 每次都從遍歷的幾個Key中選出lru最長的key。
          // 那么如何更新key的lru值呢?每次查找該key的時候就會更新該key的lru值,該值是系統(tǒng)的時間戳。
          if (bestkey == NULL || thisval > bestval) {
            bestkey = thiskey;
            bestval = thisval;
          }
        }
      }
 
 
      /* volatile-ttl */
      else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
        for (k = 0; k < server.maxmemory_samples; k++) {
          sds thiskey;
          long thisval;
 
 
          de = dictGetRandomKey(dict);
          thiskey = dictGetKey(de);
          thisval = (long) dictGetVal(de);
 
 
          /* Expire sooner (minor expire unix timestamp) is better
           * candidate for deletion */
          if (bestkey == NULL || thisval < bestval) {
            bestkey = thiskey;
            bestval = thisval;
          }
        }
      }
 
 
      ... ...
      // 到這里,要刪除的最優(yōu)key已經選出來了。現在進入刪除階段。
      // 不論哪種策略,只要選出了最優(yōu)key,就會執(zhí)行以下刪除流程。
 
 
      /* Finally remove the selected key. */
      if (bestkey) {
        long long delta;
 
 
        robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
        propagateExpire(db,keyobj);
        /* We compute the amount of memory freed by dbDelete() alone.
         * It is possible that actually the memory needed to propagate
         * the DEL in AOF and replication link is greater than the one
         * we are freeing removing the key, but we can't account for
         * that otherwise we would never exit the loop.
         *
         * AOF and Output buffer memory will be freed eventually so
         * we only care about memory used by the key space. */
        // 刪除該bestkey對應的key-value值。注意這里既要從dict中刪除,還要從expires中刪除。
        delta = (long long) zmalloc_used_memory();
        dbDelete(db,keyobj);
        delta -= (long long) zmalloc_used_memory();
        mem_freed += delta;
        server.stat_evictedkeys++;
        notifyKeyspaceEvent(REDIS_NOTIFY_EVICTED, "evicted",
          keyobj, db->id);
        decrRefCount(keyobj);
        keys_freed++;
 
 
        /* When the memory to free starts to be big enough, we may
         * start spending so much time here that is impossible to
         * deliver data to the slaves fast enough, so we force the
         * transmission here inside the loop. */
        if (slaves) flushSlavesOutputBuffers();
      }
    }
    if (!keys_freed) {
      latencyEndMonitor(latency);
      latencyAddSampleIfNeeded("eviction-cycle",latency);
      return REDIS_ERR; /* nothing to free... */
    }
  }
  latencyEndMonitor(latency);
  latencyAddSampleIfNeeded("eviction-cycle",latency);
  return REDIS_OK;
}

以上這篇關于redis Key淘汰策略的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
  • Redisredis實現排行榜功能

    redis實現排行榜功能

    排行榜在很多地方都能使用到,redis的zset可以很方便地用來實現排行榜功能,本文就來簡單的介紹一下如何使用,具有一定的參考價值,感興趣的小伙伴們...

    乘月歸5022021-08-05
  • RedisRedis如何實現數據庫讀寫分離詳解

    Redis如何實現數據庫讀寫分離詳解

    Redis的主從架構,能幫助我們實現讀多,寫少的情況,下面這篇文章主要給大家介紹了關于Redis如何實現數據庫讀寫分離的相關資料,文中通過示例代碼介紹...

    羅兵漂流記6092019-11-11
  • Redisredis 交集、并集、差集的具體使用

    redis 交集、并集、差集的具體使用

    這篇文章主要介紹了redis 交集、并集、差集的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友...

    xiaojin21cen10152021-07-27
  • RedisRedis的配置、啟動、操作和關閉方法

    Redis的配置、啟動、操作和關閉方法

    今天小編就為大家分享一篇Redis的配置、啟動、操作和關閉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    大道化簡5312019-11-14
  • RedisRedis全量復制與部分復制示例詳解

    Redis全量復制與部分復制示例詳解

    這篇文章主要給大家介紹了關于Redis全量復制與部分復制的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Redis爬蟲具有一定的參考學習...

    豆子先生5052019-11-27
  • Redis詳解Redis復制原理

    詳解Redis復制原理

    與大多數db一樣,Redis也提供了復制機制,以滿足故障恢復和負載均衡等需求。復制也是Redis高可用的基礎,哨兵和集群都是建立在復制基礎上實現高可用的...

    李留廣10222021-08-09
  • RedisRedis 事務知識點相關總結

    Redis 事務知識點相關總結

    這篇文章主要介紹了Redis 事務相關總結,幫助大家更好的理解和學習使用Redis,感興趣的朋友可以了解下...

    AsiaYe8232021-07-28
  • Redisredis中如何使用lua腳本讓你的靈活性提高5個逼格詳解

    redis中如何使用lua腳本讓你的靈活性提高5個逼格詳解

    這篇文章主要給大家介紹了關于redis中如何使用lua腳本讓你的靈活性提高5個逼格的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具...

    一線碼農5812019-11-18
主站蜘蛛池模板: 久久re热在线视频精99 | 天堂在线免费观看 | 77久久| 色婷婷久久综合中文久久一本 | 久久综合久久伊人 | 蜜桃麻豆 | 亚洲国产在线播放 | 国产综合网站 | 免费岛国片 | 电车痴汉中文字幕 | 国产精品第1页在线播放 | 草草视频在线免费观看 | 男人天堂色 | 男男playh片在线观看 | 国产66| 视频在线欧美 | 亚洲国产精久久久久久久 | 久久日韩精品无码一区 | 精品网站| 热99精品在线 | 国产高清经典露脸3p | 国产福利自产拍在线观看 | 日本视频二区 | 成人午夜影院在线观看 | 王晶经典三级 | 国产一区二区三区高清视频 | 精品日韩二区三区精品视频 | a天堂视频 | 91国语精品自产拍在线观看一 | 高跟丝袜hdvideossex| 欧美成a人片免费看久久 | 精品网站一区二区三区网站 | 国产肥老上视频 | 91赵邦贺| ady久久 | 公园暴露娇妻小说 | 花房乱爱在线观看 | 四虎在线视频免费观看 | 国产短视频精品一区二区三区 | 久久免费看少妇高潮A片2012 | 9久re在线观看视频精品 |