貴陽網(wǎng)站建設(shè)公司哪個好打開百度搜索
極客兔兔7Days
GeeCache
- Day1
-
interface{}
:任意類型 -
緩存擊穿
:一個高并發(fā)的請求查詢一個緩存中不存在的數(shù)據(jù)項,因此這個請求穿透緩存直接到達后端數(shù)據(jù)庫或數(shù)據(jù)源來獲取數(shù)據(jù)。如果這種請求非常頻繁,就會導(dǎo)致后端系統(tǒng)的負(fù)載突然增加,可能會使數(shù)據(jù)庫或數(shù)據(jù)源響應(yīng)變慢甚至宕機,從而影響整個系統(tǒng)的性能和穩(wěn)定性。- 解決1:設(shè)置熱點數(shù)據(jù)永不過期
- 解決2:使用鎖機制確保只有一個請求去訪問數(shù)據(jù)庫,其他的請求等待這個請求的結(jié)果
- 解決3:設(shè)置時間更長的二級緩存
-
緩存淘汰策略
- FIFO:先進先出,也就是淘汰緩存中最老(最早添加)的記錄
- LFU:最少使用,也就是淘汰緩存中訪問頻率最低的記錄
- LRU:最近最少使用,相對于僅考慮時間因素的 FIFO 和僅考慮訪問頻率的 LFU,LRU 算法可以認(rèn)為是相對平衡的一種淘汰算法。
-
list常用方法
:New()
、PushFront(v interface{}) *Element
、PushBack(v interface{}) *Element
、Remove(e *Element) interface{}
、Front() *Element
、Back() *Element
、Next() *Element
、Prev() *Element
-
使用list和map實現(xiàn),cache中記錄緩存最大容量和當(dāng)前數(shù)據(jù)大小,對于剛訪問的元素,將其移到list的最頭部,表示最近剛使用過,刪除時選擇最尾部的數(shù)據(jù)進行刪除,entry實際是list的節(jié)點數(shù)據(jù)類型,在刪除對應(yīng)節(jié)點后,同時刪除map中的數(shù)據(jù),實現(xiàn)查找、刪除、增加、修改功能
-
代碼
-
package geeimport "container/list"type Cache struct {maxBytes int64nbytes int64ll *list.Listcache map[string]*list.Element }type entry struct {key stringvalue Value }type Value interface {Len() int }func New(maxBytes int64) *Cache {return &Cache{maxBytes: maxBytes,ll: list.New(),nbytes: 0,cache: make(map[string]*list.Element),} }// 查找 func (c *Cache) Get(key string) (value Value, ok bool) {if ele, ok := c.cache[key]; ok {// 假設(shè)頭部是隊尾c.ll.MoveToFront(ele)kv := ele.Value.(*entry)return kv.value, true}return nil, false }// 刪除 func (c *Cache) Delete() {ele := c.ll.Back()if ele != nil {c.ll.Remove(ele)// 類型斷言kv := ele.Value.(*entry)delete(c.cache, kv.key)c.nbytes -= int64(len(kv.key)) + int64(kv.value.Len())} }// 添加 func (c *Cache) Add(key string, value Value) {if ele, ok := c.cache[key]; ok {c.ll.MoveToFront(ele)kv := ele.Value.(*entry)c.nbytes += int64(value.Len()) - int64(kv.value.Len())kv.value = value} else {ele := c.ll.PushFront(&entry{key, value})c.nbytes += int64(len(key)) + int64(value.Len())c.cache[key] = ele}for c.maxBytes != 0 && c.maxBytes < c.nbytes {c.Delete()} }func (c *Cache) Len() int {return c.ll.Len() }
-