---
title: "redis -- hash_max_zipmap_entries设置过大有问题"
author: "chenchao051"
date: "2012-11-08T14:00:25Z"
tags: []
categories: ["互联网"]
slug: "redis-hash-max-zipmap-entries"
draft: false
lastmod: "2012-11-08T14:14:18Z"
id: 1720289
url: "https://crazyjvm.iteye.com/blog/1720289"
---

使用redis时为了使用hash追求更高的内存使用率，我们一般都用hash结构，并且有时候会把hash\_max\_zipmap\_entries这个值设置的很大，很多资料也推荐设置到1000，默认设置为了512，但是这里有个坑

 

```
#define ZIPMAP_BIGLEN 254
#define ZIPMAP_END 255
```

 

 

```
/* Return the number of entries inside a zipmap */
unsigned int zipmapLen(unsigned char *zm) {
    unsigned int len = 0;
    if (zm[0] < ZIPMAP_BIGLEN) {
        len = zm[0]; //假如subkey个数少于254，直接取出
    } else {
        unsigned char *p = zipmapRewind(zm);
        while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;//不然的话，完整遍历
        /* Re-store length if small enough */
        if (len < ZIPMAP_BIGLEN) zm[0] = len;
    }
    return len;
}
```

 

 

 

看到没，同志们，当zm的subkey数超过ZIPMAP\_BIGLEN时，你就悲剧了，每次获得zm的subkey的个数都得去遍历整个zipmap。假如大量并发查询到zm时，都需要去完整遍历zm，结果就是CPU像打了鸡血一样的上去了。

 

 

推荐几个文章：

[http://stackoverflow.com/questions/10004565/redis-10x-more-memory-usage-than-data](http://stackoverflow.com/questions/10004565/redis-10x-more-memory-usage-than-data)（为什么redis中内存比文件大）

[http://www.searchtb.com/2011/05/redis-storage.html](http://www.searchtb.com/2011/05/redis-storage.html)（源码分析） 

[http://www.oschina.net/question/12\_31910](http://www.oschina.net/question/12_31910)（容量估计）

[http://www.mysqlops.com/2011/09/01/redis-hash-table.html](http://www.mysqlops.com/2011/09/01/redis-hash-table.html)（ht分析）

[http://www.open-open.com/bbs/view/1321697543077](http://www.open-open.com/bbs/view/1321697543077)（zipmap分析）

[http://stackoverflow.com/questions/8963372/how-to-save-and-retrieve-string-with-accents-in-redis](http://stackoverflow.com/questions/8963372/how-to-save-and-retrieve-string-with-accents-in-redis)（编码问题）

```

```