FileCacheService - Generic File-Based Caching Service
Overview
The FileCacheService is a reusable, generic file-based caching service that provides persistent JSON data storage with configurable time-to-live (TTL). It abstracts away the complexity of file I/O, cache validation, and TTL management, making it easy to add caching to any service.
Features
- Generic JSON Storage: Stores any data as JSON objects
- Configurable TTL: Set cache expiration time in hours (default: 24 hours)
- Automatic Directory Management: Creates cache directories if they don’t exist
- Thread-Safe File Operations: Safe for concurrent access
- Comprehensive Logging: Detailed logs for debugging and monitoring
- Error Handling: Graceful error handling with meaningful error messages
Usage Example
#include <file_cache_service.hpp>
using namespace sravz::services::cache;
// Create a cache service with 24-hour TTL
auto cache = std::make_shared<FileCacheService>(
"/tmp/my-cache", // Cache directory
"data.json", // Cache filename
24 // TTL in hours
);
// Check if cache is valid
if (cache->isCacheValid()) {
// Load from cache
auto data = cache->loadFromCache();
if (data) {
// Use cached data
process(*data);
}
} else {
// Load fresh data
auto fresh_data = loadFromSource();
// Save to cache
cache->saveToCache(fresh_data);
}
API Reference
Constructor
FileCacheService(
const std::string& cache_directory,
const std::string& cache_filename,
int ttl_hours = 24
);
Methods
isCacheValid() -> bool- Checks if cache exists and is not expiredloadFromCache() -> std::optional<boost::json::object>- Loads cached datasaveToCache(const boost::json::object& data) -> bool- Saves data to cacheclearCache() -> bool- Deletes the cache filegetCacheFilePath() -> std::string- Gets full path to cache filegetTTLHours() -> int- Gets configured TTL in hours
Integration with Services
The QuotesService demonstrates how to integrate FileCacheService:
class QuotesService {
public:
QuotesService(
std::shared_ptr<MongoClient> mongoClient,
const std::string& cache_directory
) : mongoClient_(mongoClient) {
// Initialize FileCacheService
fileCache_ = std::make_shared<FileCacheService>(
cache_directory,
"quotes_cache.json",
24 // 24-hour TTL
);
}
std::unordered_map<std::string, QuoteData> getAllQuotes() {
// Use FileCacheService for caching
if (fileCache_->isCacheValid()) {
return loadFromCache();
}
return refreshFromDatabase();
}
private:
std::shared_ptr<FileCacheService> fileCache_;
std::shared_ptr<MongoClient> mongoClient_;
};
Performance Benefits
- Reduced Database Load: Caching frequently accessed data reduces database queries
- Fast Retrieval: File system access is much faster than network database calls
- Offline Capability: Cached data remains available even if database is unreachable
Use Cases
- Quote Data Caching: Cache market quotes for 24 hours
- User Session Caching: Short-lived cache (1 hour)
- Configuration Caching: Long-lived cache (7 days)
- Analytics Data Caching: Daily statistics cache
See Also
- PnL Controller - Portfolio profit/loss calculations
- Quotes Analytics API - Market analytics
- MongoDB Service - Database integration
