C++ 代码实现高效缓存系统

实现一个高效的缓存系统需要考虑多种因素,包括缓存替换策略、缓存大小管理、并发访问控制等。下面是一个简单的C++代码示例,展示了一个支持LRU(最近最少使用)替换策略的缓存系统

#include <iostream>
#include <unordered_map>
#include <list>

template<typename Key, typename Value>
class LRUCache {
public:
    LRUCache(int capacity) : capacity(capacity) {}

    Value get(const Key& key) {
        auto it = cache.find(key);
        if (it == cache.end()) {
            return Value();
        } else {
            // Move accessed key to the front of the list
            accessOrder.splice(accessOrder.begin(), accessOrder, it->second);
            return it->second->second;
        }
    }

    void put(const Key& key, const Value& value) {
        auto it = cache.find(key);
        if (it != cache.end()) {
            // Update existing key's value and move it to the front of the list
            it->second->second = value;
            accessOrder.splice(accessOrder.begin(), accessOrder, it->second);
        } else {
            if (cache.size() == capacity) {
                // Evict least recently used key
                auto& leastRecent = accessOrder.back();
                cache.erase(leastRecent.first);
                accessOrder.pop_back();
            }
            // Insert new key-value pair to the front of the list
            accessOrder.emplace_front(key, value);
            cache[key] = accessOrder.begin();
        }
    }

private:
    int capacity;
    std::unordered_map<Key, typename std::list<std::pair<Key, Value>>::iterator> cache;
    std::list<std::pair<Key, Value>> accessOrder;
};

int main() {
    LRUCache<int, std::string> cache(2);
    cache.put(1, "foo");
    cache.put(2, "bar");
    std::cout << cache.get(1) << std::endl;  // Output: foo
    cache.put(3, "baz");
    std::cout << cache.get(2) << std::endl;  // Output: bar (recently used)
    std::cout << cache.get(3) << std::endl;  // Output: baz
    cache.put(4, "qux");
    std::cout << cache.get(1) << std::endl;  // Output: "" (not found)
    std::cout << cache.get(3) << std::endl;  // Output: baz
    std::cout << cache.get(4) << std::endl;  // Output: qux
    return 0;
}

这个示例实现了一个LRU缓存系统,使用了哈希表和双向链表来实现高效的查找和插入操作。你可以根据需要扩展此示例,添加其他缓存替换策略,如LFU(最少使用)或FIFO(先进先出),并添加并发访问控制和缓存大小管理功能。

Python 代码实现高效缓存系统

使用了Python的OrderedDict来实现LRU缓存系统。缓存的键值对以最近访问的顺序排列,每次访问一个元素时,将其移到字典的末尾,保持最近访问的元素在最后。当插入新元素时,如果容量已满,则删除最久未被访问的元素。

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache:
            return None
        value = self.cache.pop(key)
        self.cache[key] = value
        return value

    def put(self, key, value):
        if key in self.cache:
            self.cache.pop(key)
        elif len(self.cache) >= self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = value

# Example usage:
cache = LRUCache(2)
cache.put(1, 'foo')
cache.put(2, 'bar')
print(cache.get(1))  # Output: foo
cache.put(3, 'baz')
print(cache.get(2))  # Output: None (key 2 is evicted)
print(cache.get(3))  # Output: baz

Java 代码实现高效缓存系统

使用Java的LinkedHashMap来实现LRU缓存系统。LinkedHashMap本身就具有按照访问顺序排序的特性,因此可以直接利用它来实现LRU缓存。在LRUCache类中重写了removeEldestEntry方法来控制是否删除最老的条目。

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(2);
        cache.put(1, "foo");
        cache.put(2, "bar");
        System.out.println(cache.get(1));  // Output: foo
        cache.put(3, "baz");
        System.out.println(cache.get(2));  // Output: null (key 2 is evicted)
        System.out.println(cache.get(3));  // Output: baz
    }
}