0.前言
redis是KV型的記憶體資料庫, 資料庫儲存的核心就是Hash表, 我們執行select指令選擇一個儲存的db之後, 所有的操作都是以hash表為基礎的, 下面會分析下redis的hash資料結構與實作.
#1.hash資料結構
/*Hash表一个节点包含Key,Value数据对 */ typedef struct dictEntry { void *key; union { void *val; uint64_t u64; int64_t s64; double d; } v; struct dictEntry *next; /* 指向下一个节点, 链接表的方式解决Hash冲突 */ } dictEntry; /* 存储不同数据类型对应不同操作的回调函数 */ typedef struct dictType { unsigned int (*hashFunction)(const void *key); void *(*keyDup)(void *privdata, const void *key); void *(*valDup)(void *privdata, const void *obj); int (*keyCompare)(void *privdata, const void *key1, const void *key2); void (*keyDestructor)(void *privdata, void *key); void (*valDestructor)(void *privdata, void *obj); } dictType; typedef struct dictht { dictEntry **table; /* dictEntry*数组,Hash表 */ unsigned long size; /* Hash表总大小 */ unsigned long sizemask; /* 计算在table中索引的掩码, 值是size-1 */ unsigned long used; /* Hash表已使用的大小 */ } dictht; typedef struct dict { dictType *type; void *privdata; dictht ht[2]; /* 两个hash表,rehash时使用*/ long rehashidx; /* rehash的索引, -1表示没有进行rehash */ int iterators; /* */ } dict;
2.hash資料結構圖
#3.漸進式hash說明
dict中ht[2]中有兩個hash表, 我們第一次儲存資料的資料時, ht[0]會建立一個最小為4的hash表, 一旦ht[0]中的size和used相等, 則dict中會在ht[1]建立一個size*2大小的hash表, 此時並不會直接將ht[ 0]中的資料copy進ht[0]中, 執行的是漸進式rehash, 即在以後的操作(find, set, get等)中慢慢的copy進去, 以後新加入的元素會加入ht[ 0], 因此在ht[1]被佔滿的時候定能確保ht[0]中所有的資料全部copy到ht[1]中.
4.建立hash表
建立hash表過程非常簡單,直接呼叫dictCreate函數, 分配一塊記憶體,初始化中間變數即可.
dict *dictCreate(dictType *type, void *privDataPtr) { /*分配内存*/ dict *d = zmalloc(sizeof(*d)); /*初始化操作*/ _dictInit(d,type,privDataPtr); return d; }
5.新增元素
hash表中新增元素,先判斷空間是否足夠, 然後計算key對應的hash值, 然後將需要添加的key和value放入表中.
int dictAdd(dict *d, void *key, void *val) { /*添加入hash表中, 返回新添加元素的实体结构体*/ dictEntry *entry = dictAddRaw(d,key); if (!entry) return DICT_ERR; /*元素val值放入元素实体结构中*/ dictSetVal(d, entry, val); return DICT_OK; } /* *添加元素实体函数 */ dictEntry *dictAddRaw(dict *d, void *key) { int index; dictEntry *entry; dictht *ht; if (dictIsRehashing(d)) _dictRehashStep(d); /*根据key值计算新元素在hash表中的索引, 返回-1则表示元素已存在, 直接返回NULL*/ if ((index = _dictKeyIndex(d, key)) == -1) return NULL; /*如果在进行rehash过程,则新元素添加到ht[1]中, 否则添加到ht[0]中 */ ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0]; entry = zmalloc(sizeof(*entry)); entry->next = ht->table[index]; ht->table[index] = entry; ht->used++; /*设置元素key*/ dictSetKey(d, entry, key); return entry; } /* *计算索引的函数 */ static int _dictKeyIndex(dict *d, const void *key) { unsigned int h, idx, table; dictEntry *he; /* 判断hash表是否空间足够, 不足则需要扩展 */ if (_dictExpandIfNeeded(d) == DICT_ERR) return -1; /* 计算key对应的hash值 */ h = dictHashKey(d, key); for (table = 0; table <= 1; table++) { /*计算索引*/ idx = h & d->ht[table].sizemask; /*遍历冲突列表, 判断需要查找的key是否已经在冲突列表中*/ he = d->ht[table].table[idx]; while(he) { if (dictCompareKeys(d, key, he->key)) return -1; he = he->next; } if (!dictIsRehashing(d)) break; } return idx; } /* *判断hash表是否需要扩展空间 */ static int _dictExpandIfNeeded(dict *d) { /*redis的rehash采用的渐进式hash, rehash时分配了原来两倍的内存空间, 在rehash阶段空间必定够用*/ if (dictIsRehashing(d)) return DICT_OK; /* hash表是空的需要初始化空间, 默认是4*/ if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE); /* 已使用空间满足不了设置的条件*/ if (d->ht[0].used >= d->ht[0].size && (dict_can_resize || d->ht[0].used/d->ht[0].size > dict_force_resize_ratio)) { /*扩展空间, 使用空间的两倍*/ return dictExpand(d, d->ht[0].used*2); } return DICT_OK; } /* *扩展空间或者初始化hash表空间 */ int dictExpand(dict *d, unsigned long size) { dictht n; /* 对需要分配大小圆整为2的倍数 */ unsigned long realsize = _dictNextPower(size); /* 如果空间足够则表明调用错误 */ if (dictIsRehashing(d) || d->ht[0].used > size) return DICT_ERR; n.size = realsize; n.sizemask = realsize-1; n.table = zcalloc(realsize*sizeof(dictEntry*)); n.used = 0; /*hash表为空初始化hash表*/ if (d->ht[0].table == NULL) { d->ht[0] = n; return DICT_OK; } /*新分配的空间放入ht[1], 后面一步一步进行rehash*/ d->ht[1] = n; d->rehashidx = 0; return DICT_OK; }
6.查找元素
查找元素過程,首先計算hash值, 然後計算在ht[0]和ht[1]中索引位置, 進行查找.
dictEntry *dictFind(dict *d, const void *key) { dictEntry *he; unsigned int h, idx, table; if (d->ht[0].size == 0) return NULL; /*如果正在进行rehash, 执行一次rehash*/ if (dictIsRehashing(d)) _dictRehashStep(d); h = dictHashKey(d, key); /*由于可能正在rehash, 因此要从ht[0]和ht[1]中分别进行查找, 找不到返回NULL*/ for (table = 0; table <= 1; table++) { idx = h & d->ht[table].sizemask; he = d->ht[table].table[idx]; /*遍历冲突列表查找元素*/ while(he) { if (dictCompareKeys(d, key, he->key)) return he; he = he->next; } if (!dictIsRehashing(d)) return NULL; } return NULL; }
7.刪除元素
刪除元素首先查找元素, 然後將元素從hash表中移除即可, 呼叫dictDelete刪除元素, 會同時刪除元素所佔空間
int dictDelete(dict *ht, const void *key) { return dictGenericDelete(ht,key,0); } static int dictGenericDelete(dict *d, const void *key, int nofree) { unsigned int h, idx; dictEntry *he, *prevHe; int table; if (d->ht[0].size == 0) return DICT_ERR; if (dictIsRehashing(d)) _dictRehashStep(d); h = dictHashKey(d, key); for (table = 0; table <= 1; table++) { idx = h & d->ht[table].sizemask; he = d->ht[table].table[idx]; prevHe = NULL; /*查找元素到元素,进行删除操作, 并释放占用的内存*/ while(he) { if (dictCompareKeys(d, key, he->key)) { /* Unlink the element from the list */ if (prevHe) prevHe->next = he->next; else d->ht[table].table[idx] = he->next; if (!nofree) { dictFreeKey(d, he); dictFreeVal(d, he); } zfree(he); d->ht[table].used--; return DICT_OK; } prevHe = he; he = he->next; } if (!dictIsRehashing(d)) break; } return DICT_ERR; /* not found */ }
hash指令
hash指令操作都比較簡單,需要注意的是當我們建立hash表示預設儲存結構,不是dict,而是ziplist結構,可以參考redis之Ziplist資料結構,hash_max_ziplist_entries和hash_max_ziplist_value值作為閥值,hash_max_ziplist_entries表示一旦ziplist中元素數量超過該值,則需要轉換為diccigmaxv_vvmax表示一旦ziplist中資料長度大於該值,則需要轉換為dict結構。
更多Redis相關技術文章,請造訪Redis教學欄位學習!
以上是redis的hash怎麼實現的的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Redis脫穎而出是因為其高速、多功能性和豐富的數據結構。 1)Redis支持字符串、列表、集合、散列和有序集合等數據結構。 2)它通過內存存儲數據,支持RDB和AOF持久化。 3)從Redis6.0開始引入多線程處理I/O操作,提升了高並發場景下的性能。

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis通過緩存數據、實現分佈式鎖和數據持久化來提升應用性能和可擴展性。 1)緩存數據:使用Redis緩存頻繁訪問的數據,提高數據訪問速度。 2)分佈式鎖:利用Redis實現分佈式鎖,確保在分佈式環境中操作的安全性。 3)數據持久化:通過RDB和AOF機制保證數據安全性,防止數據丟失。

Redis的數據模型和結構包括五種主要類型:1.字符串(String):用於存儲文本或二進制數據,支持原子操作。 2.列表(List):有序元素集合,適合隊列和堆棧。 3.集合(Set):無序唯一元素集合,支持集合運算。 4.有序集合(SortedSet):帶分數的唯一元素集合,適用於排行榜。 5.哈希表(Hash):鍵值對集合,適合存儲對象。

Redis的數據庫方法包括內存數據庫和鍵值存儲。 1)Redis將數據存儲在內存中,讀寫速度快。 2)它使用鍵值對存儲數據,支持複雜數據結構,如列表、集合、哈希表和有序集合,適用於緩存和NoSQL數據庫。

Redis是一個強大的數據庫解決方案,因為它提供了極速性能、豐富的數據結構、高可用性和擴展性、持久化能力以及廣泛的生態系統支持。 1)極速性能:Redis的數據存儲在內存中,讀寫速度極快,適合高並發和低延遲應用。 2)豐富的數據結構:支持多種數據類型,如列表、集合等,適用於多種場景。 3)高可用性和擴展性:支持主從復制和集群模式,實現高可用性和水平擴展。 4)持久化和數據安全:通過RDB和AOF兩種方式實現數據持久化,確保數據的完整性和可靠性。 5)廣泛的生態系統和社區支持:擁有龐大的生態系統和活躍社區,

Redis的關鍵特性包括速度、靈活性和豐富的數據結構支持。 1)速度:Redis作為內存數據庫,讀寫操作幾乎瞬時,適用於緩存和會話管理。 2)靈活性:支持多種數據結構,如字符串、列表、集合等,適用於復雜數據處理。 3)數據結構支持:提供字符串、列表、集合、哈希表等,適合不同業務需求。

Redis的核心功能是高性能的內存數據存儲和處理系統。 1)高速數據訪問:Redis將數據存儲在內存中,提供微秒級別的讀寫速度。 2)豐富的數據結構:支持字符串、列表、集合等,適應多種應用場景。 3)持久化:通過RDB和AOF方式將數據持久化到磁盤。 4)發布訂閱:可用於消息隊列或實時通信系統。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器