C++ 缓存:Redis、Memcached 及内置解决方案:从入门到精通

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么 C++ 需要缓存?



在现代高负载软件中,数据访问速度至关重要。无论是处理数百万请求的 Web 服务器,还是高频交易终端——每一次多余的数据库查询或慢速磁盘访问都可能成为瓶颈。此时,缓存技术便应运而生——它将频繁请求的数据存储在高速内存(RAM)中,以便后续即时访问。



C++ 语言为开发者构建高效缓存系统提供了独特的能力:从精细的内存控制到使用强大的外部工具。在本文中,我们将从简单的内置解决方案逐步深入到 Redis 和 Memcached 等工业级系统,并分析何时以及如何选择合适的方法。



您将了解到:

  • 如何在不使用第三方库的情况下在 C++ 中实现简单缓存。
  • 如何连接并使用 Redis 和 Memcached。
  • 每种方法的性能对比及应用场景。


内置解决方案:用 C++ 实现自己的缓存



在连接外部服务之前,有必要了解对于许多任务而言,内置缓存已经足够。其主要优势包括:零网络延迟、部署简单以及对数据的完全控制。



基于 std::unordered_map 的最简缓存

最基本的方案是使用关联数组。然而,它没有数据淘汰机制(eviction policy),会无限增长,可能导致内存溢出。



#include <unordered_map>#include <string>

class SimpleCache { std::unordered_map<std::string, std::string> cache_;public: void put(const std::string& key, const std::string& value) { cache_[key] = value; } std::string get(const std::string& key) { auto it = cache_.find(key); if (it != cache_.end()) { return it->second; } return ""; // 或抛出异常 }};


LRU 缓存(最近最少使用)

更高级的解决方案是 LRU 缓存,它在达到容量限制时删除最近最少使用的元素。实现需要结合哈希表和双向链表。



#include <list>#include <unordered_map>

template<typename K, typename V>class LRUCache { size_t capacity_; std::list<std::pair<K, V>> items_; std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> cache_;

public: LRUCache(size_t cap) : capacity_(cap) {}

V get(const K& key) { auto it = cache_.find(key); if (it == cache_.end()) { throw std::runtime_error("Key not found"); } items_.splice(items_.begin(), items_, it->second); return it->second->second; }

void put(const K& key, const V& value) { auto it = cache_.find(key); if (it != cache_.end()) { it->second->second = value; items_.splice(items_.begin(), items_, it->second); return; } if (items_.size() == capacity_) { auto last = items_.back(); cache_.erase(last.first); items_.pop_back(); } items_.emplace_front(key, value); cache_[key] = items_.begin(); }};


这种缓存在单进程环境中非常理想,此时数据仅属于该进程且无需同步。



Memcached:适用于简单数据的分布式缓存



Memcached 是一个轻量级、高性能的缓存系统,基于 TCP/UDP 协议运行。它将数据存储在 RAM 中,不支持持久化。非常适合缓存

博客

书籍推荐