借助 PriorityQueue 实现简单的 LRU Cache

借助 PriorityQueue 实现简单的 Lru Cache

Intro

在使用缓存的时候往往要考虑缓存限制以免缓存过多地占用应用内存而且这样缓存的效率可能并不够高

比较常见的做法是实现缓存驱逐/淘汰,比如 LRU Cache,redis 默认的内存策略也是基于 lru 的 allkeys-lru,

.NET 6 开始引入了 PriorityQueue 这一数据结构 .NET6 中的 PriorityQueue,在 .NET 9 中支持了 Remove .NET 9 Preview 1 PriorityQueue 更新,我们可以通过 Remove + enqueue 来实现 update priority 的需要,今天我们就借助 .NET 里的 PriorityQueue 来实现 LRU cache

Samples

首先我们来看下基于 PriorityQueue 的 LruCache 简单实现

file interface ICache
{
    void PrintKeys();
    void Set(string key, object? value);
    bool TryGetValue<TValue>(string key, [MaybeNullWhen(false)] out TValue value);
}

file sealed class LruCache(int maxSize) : ICache
{
    private readonly ConcurrentDictionary<string, object?> _store = new();
    private readonly PriorityQueue<string, long> _priorityQueue = new PriorityQueue<string, long>();
    private readonly JsonSerializerOptions _jsonSerializerOptions = new()
    {
        WriteIndented = true
    };

    public ICollection<string> Keys => _store.Keys;

    public void PrintKeys()
    {
        Console.WriteLine("PrintKeys:");
        Console.WriteLine(JsonSerializer.Serialize(_store, _jsonSerializerOptions));
    }

    public void Set(string key, object? value)
    {
        if (_store.ContainsKey(key))
        {
            _store[key] = value;
            UpdateKeyAccess(key);
            return;
        }

        while (_store.Count >= maxSize)
        {
            var keyToRemove = _priorityQueue.Dequeue();
            _store.TryRemove(keyToRemove, out _);
        }

        _store[key] = value;
        UpdateKeyAccess(key);
    }

    public bool TryGetValue<TValue>(string key, [MaybeNullWhen(false)] out TValue value)
    {
        if (!_store.TryGetValue(key, out var cacheValue))
        {
            value = default;
            return false;
        }

        UpdateKeyAccess(key);

        value = (TValue)cacheValue!;
        return true;
    }

    private void UpdateKeyAccess(string key)
    {
        _priorityQueue.Remove(key, out _, out _);
        _priorityQueue.Enqueue(key, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
    }
}

cache 主要定义了 Get/Set 两个方法,LruCache 设置了最大的 cache 数量,简单的按照 key 的数量来计算,没有计算实际的内存占用等

用了一个 ConcurrentDictionary 来存 cache,这里的 cache 出于简单考虑不设置过期时间,只根据 cache keys limit 来计算,使用 PriorityQueue 来保存缓存最近一次访问的时间以根据访问的时间来决定需要驱逐的时候谁应该被驱逐

来看一个简单的使用示例:

var cache = new LruCache(2);
cache.Set("name", "test");
cache.Set("age", "10");
cache.PrintKeys();

ConsoleHelper.HandleInputLoop(x =>
{
    if (x.StartsWith("get:"))
    {
        var key = x["get:".Length..];
        cache.TryGetValue(key, out string? value);
        Console.WriteLine($"key: {key}, value: {value}");
        return;
    }

    cache.Set(x, "Hello .NET");

    cache.PrintKeys();
}, "Input something to test lruCache,  starts with 'get:' to try get cache value, otherwise set cache, input q to exit");
ConsoleHelper.ReadLine();

ConsoleHelper.HandInputLoop 是一个帮助方法,可以不断的从 console 读取 Input 并进行一定的处理,默认输出 q 来退出循环,我们执行一下看下效果

bf8cac3a33736c7ade113a3b37e4de36.png

output

首先先打印了一下缓存的数据,我们开始设置了 age 和 name 两个缓存值,然后通过输入循环来设置新的缓存和访问某一个缓存,

首先我们设置了一个 aa 缓存,因为我们设置了最多保留两个缓存而且缓存中已经有了两个缓存,这样我们就需要驱逐一个 key 才能设置新的 key,首先加入的 key 被认为是最早访问的一个 key 应该被驱逐,所以 name 被移除了,然后新的 key aa 被加入到缓存中

之后我们再次设置了 aa ,因为之前已经在缓存里了,无需驱逐缓存,可以直接更新已有的缓存并更新最后访问的时间

接着我们访问了一下 age 缓存,这样我们最近访问的缓存就变成了它,下次有新的缓存进来就不应该淘汰 age 缓存

之后我们设置一个 aaa 缓存,从输出结果可以看到,此时缓存中的 key 是 age/aaa,aa 的访问时间较早所以被淘汰了

我们再来设置一下 aa,此时 age 就被淘汰了,缓存中剩下 aaa/aa

这里我们只是记录了一下最后的访问时间,我们也可以记录下访问的次数,根据访问时间+访问次数做一个权重计算一个综合之后的优先级,这样就比单独按照时间来计算更加具体参考意义,你觉得有别的需要记录也可以考虑记录下来,然后通过自定义比较器来决定谁应该被驱逐谁应该被保留

下面是一个带有访问次数的一个 lru cache 的示例

file sealed record CacheAccessEntry
{
    public int AccessCount { get; set; }
    public long AccessTimestamp { get; set; }
}

file sealed class CacheAccessEntryComparer(Func<CacheAccessEntry, long>? priorityFactory) : IComparer<CacheAccessEntry>
{
    public CacheAccessEntryComparer() : this(null)
    {
    }

    public int Compare(CacheAccessEntry? x, CacheAccessEntry? y)
    {
        ArgumentNullException.ThrowIfNull(x);
        ArgumentNullException.ThrowIfNull(y);

        if (priorityFactory is not null)
        {
            return priorityFactory(x).CompareTo(priorityFactory(y));
        }

        if (x.AccessCount == y.AccessCount)
        {
            return x.AccessTimestamp == y.AccessTimestamp
                ? 0
                : (x.AccessTimestamp > y.AccessTimestamp ? 1 : -1)
                ;
        }
        return x.AccessCount > y.AccessCount ? 1 : -1;
    }
}

file sealed class LruCacheV2(int maxSize) : ICache
{
    private readonly ConcurrentDictionary<string, object?> _store = new();
    private static readonly CacheAccessEntryComparer CacheEntryComparer = new();
    private readonly PriorityQueue<string, CacheAccessEntry> _priorityQueue =
        new(CacheEntryComparer);

    public ICollection<string> Keys => _store.Keys;

    public void PrintKeys()
    {
        Console.WriteLine("PrintKeys:");
        Console.WriteLine(JsonSerializer.Serialize(_store));
    }

    public void Set(string key, object? value)
    {
        if (_store.ContainsKey(key))
        {
            _store[key] = value;
            UpdateKeyAccess(key);
            return;
        }

        while (_store.Count >= maxSize)
        {
            var keyToRemove = _priorityQueue.Dequeue();
            _store.TryRemove(keyToRemove, out _);
        }

        _store[key] = value;
        UpdateKeyAccess(key);
    }

    public bool TryGetValue<TValue>(string key, [MaybeNullWhen(false)] out TValue value)
    {
        if (!_store.TryGetValue(key, out var cacheValue))
        {
            value = default;
            return false;
        }

        UpdateKeyAccess(key);

        value = (TValue)cacheValue!;
        return true;
    }

    private void UpdateKeyAccess(string key)
    {
        _priorityQueue.Remove(key, out _, out var entry);

        entry ??= new();
        entry.AccessTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        entry.AccessCount += 1;
        _priorityQueue.Enqueue(key, entry);
    }
}

使用示例和前面类似,只需要把 LruCache 改成 LruCacheV2 即可

var cache = new LruCacheV2(2);
cache.Set("name", "test");
cache.Set("age", "10");
cache.PrintKeys();

ConsoleHelper.HandleInputLoop(x =>
{
    if (x.StartsWith("get:"))
    {
        var key = x["get:".Length..];
        cache.TryGetValue(key, out string? value);
        Console.WriteLine($"key: {key}, value: {value}");
        return;
    }

    cache.Set(x, "Hello .NET");

    cache.PrintKeys();
}, "Input something to test lruCache,  starts with 'get:' to try get cache value, otherwise set cache, input q to exit");

执行结果如下:

85b55f784307a85574b43122dab79746.png

v2 output

这里我们针对 age 访问了两次,虽然之后访问了 aaaa 的最后访问时间是最新的,但是访问次数较少,V2 版本默认优先了访问次数,导致 age 的驱逐优先级低于 aa, aa 被淘汰

以上示例仅作参考,具体代码可以从文末的 Github 链接获取,实际要实现缓存的驱逐建议只是标记一下已删除,实际删除工作交给后台任务去执行,以免缓存驱逐的过程导致性能问题

References

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LFU (Least Frequently Used) 和 LRU (Least Recently Used) 都是常见的缓存淘汰策略,它们可以用 PriorityQueue(优先队列)来实现。 LFU 的思想是,当缓存空间满时,淘汰掉最不经常使用的缓存。具体实现时,我们可以使用一个字典来记录每个缓存的访问次数,然后将缓存按照访问次数从小到大排序,淘汰访问次数最小的缓存。 LRU 的思想是,当缓存空间满时,淘汰最近最少使用的缓存。具体实现时,我们可以使用一个双向链表和一个字典来记录缓存的顺序和存储的位置。每当访问一个缓存时,将其移动到链表头部;当缓存空间满时,淘汰链表尾部的缓存。 下面是使用 PriorityQueue 实现 LFU 和 LRU 的 Python 代码示例: LFU: ```python import heapq class LFUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.freq = {} self.count = 0 def get(self, key: int) -> int: if key not in self.cache: return -1 self.freq[key] += 1 heapq.heapify(self.cache[key]) return self.cache[key][0] def put(self, key: int, value: int) -> None: if self.capacity == 0: return if key in self.cache: self.cache[key].append(value) self.freq[key] += 1 heapq.heapify(self.cache[key]) else: if self.count == self.capacity: min_freq = min(self.freq.values()) for k, v in self.freq.items(): if v == min_freq: del self.cache[k] del self.freq[k] break self.count -= 1 self.cache[key] = [value] self.freq[key] = 1 self.count += 1 ``` LRU: ```python class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key not in self.cache: return -1 node = self.cache[key] self._remove(node) self._add(node) return node.val def put(self, key: int, value: int) -> None: if key in self.cache: self._remove(self.cache[key]) node = Node(key, value) self.cache[key] = node self._add(node) if len(self.cache) > self.capacity: node = self.head.next self._remove(node) del self.cache[node.key] def _remove(self, node): node.prev.next = node.next node.next.prev = node.prev def _add(self, node): node.prev = self.tail.prev node.next = self.tail self.tail.prev.next = node self.tail.prev = node class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值