Preface
I wrote an article LRU cache
a few years ago:
https://crossoverjie.top/2018/04/07/algorithm/LRU-cache/
It was implemented in Java at the time. Recently, when I was perfecting , I just needed a least recently used data structure to store historical records.
ptg: Performance testing tool (Go), a gRPC client debugging tool implemented in Go.
There is no related implementation in the official Go library. Considering the simplicity of the program, I don't plan to rely on a third-party library. I write one myself; the complexity is not high, and there are few lines of code.
With this data structure, I implemented the request history function
Store each request record in the lru cache, the most recently used history record is ranked first, and it can also provide related search functions; see the figure below for details.
accomplish
There is nothing to say about the implementation principle, Java
the same as that of 061c00e86ab36e:
- The order in which data is stored in a doubly linked list
- A
map
stores the final data - Remove the tail data of the linked list when the data reaches the upper limit
- Move the used
Node
to the head node of the linked list
Although Go is relatively concise, the good news is that the basic doubly linked list structure is still available.
So based on this, a LruCache
defined:
According to the previous analysis:
size
stores the cache size.- The linked list stores the order of data.
map
stores data.lock
used to control concurrency security.
The next focus is on two functions: write and query.
When writing, it is judged whether the upper limit of the capacity is reached, and the tail data is deleted when it is reached; otherwise, the data is written to the head.
When fetching data, this will move the queried node to the head node.
These node operations are encapsulated by List.
So it is more convenient to use.
In the end, LruCache
. If you want to know more details, you can refer to the source code:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。