WebAPI 2能否配置2天内存缓存?求48小时缓存最优机制
Absolutely, you can use in-memory caching with a 48-hour expiry in WebAPI 2. The catch you've noticed—where MemoryCache.Default gets cleared after 20 minutes—isn't a limitation of the cache itself, but of your IIS app pool's default idle timeout setting. Let's walk through the best mechanisms to implement a reliable 48-hour cache:
1. Configure MemoryCache with Explicit 48-Hour Expiry
First, let's set up the cache correctly to enforce a 48-hour absolute expiration. Here's a reusable cache service example using System.Runtime.Caching:
using System.Runtime.Caching; public class InMemoryCacheService { private readonly ObjectCache _cache; public InMemoryCacheService() { _cache = MemoryCache.Default; } // Add item to cache with 48-hour absolute expiry public void CacheItem(string key, object data) { var cachePolicy = new CacheItemPolicy { // Use UtcNow to avoid timezone issues AbsoluteExpiration = DateTimeOffset.UtcNow.AddHours(48), // Optional: Add a callback if you need to handle cache eviction events // RemovedCallback = OnCacheItemRemoved }; _cache.Set(key, data, cachePolicy); } // Retrieve item from cache public T GetCachedItem<T>(string key) where T : class { return _cache.Get(key) as T; } }
This ensures the cache item will expire exactly 48 hours after being added—but only if the app pool doesn't recycle before then. That's where we need to address the app pool settings.
2. Adjust IIS App Pool Settings to Prevent Premature Cache Loss
Since in-memory cache is tied to the app's process, any app pool recycle (from idle timeout, memory limits, or scheduled recycling) will wipe the entire cache. To fix this:
- Increase/Disable Idle Timeout:
Open IIS Manager → Find your app pool → Right-click → Advanced Settings. Under Process Model, set Idle Time-out (minutes) to0(never times out) or a value greater than2880(48 hours in minutes). - Disable/Adjust Scheduled Recycling:
Under the Recycling section, set Regular Time Interval (minutes) to0to disable scheduled recycling, or set it to a value longer than 48 hours. - Tweak Memory Limits:
If your app pool recycles due to high memory usage, increase the Private Memory Limit (KB) or Virtual Memory Limit (KB) to match your app's needs.
Keep in mind: Adjusting these settings may increase resource usage on your server, so balance this with your server's capacity.
3. Distributed Cache: The Best Option for Reliable Long-Term Caching
If you can't modify app pool settings, or if you're running multiple WebAPI instances (load-balanced), in-memory cache won't work reliably. In this case, use a distributed cache—it stores data outside the app process, so app pool recycles won't affect it, and it works across multiple instances.
Redis is the most popular choice here. Here's a quick example using StackExchange.Redis (install the NuGet package first):
using StackExchange.Redis; using Newtonsoft.Json; public class RedisCacheService { private readonly IDatabase _redisDb; public RedisCacheService() { // Connect to your Redis instance (update the connection string as needed) var connection = ConnectionMultiplexer.Connect("localhost:6379"); _redisDb = connection.GetDatabase(); } public void CacheItem(string key, object data) { var serializedData = JsonConvert.SerializeObject(data); // Set 48-hour expiry _redisDb.StringSet(key, serializedData, TimeSpan.FromHours(48)); } public T GetCachedItem<T>(string key) where T : class { var cachedValue = _redisDb.StringGet(key); return cachedValue.HasValue ? JsonConvert.DeserializeObject<T>(cachedValue) : null; } }
Distributed cache is the more robust solution for long-term caching scenarios, especially in scalable environments.
Final Recommendation
- Use configured MemoryCache + adjusted app pool settings if you're running a single instance and can control IIS settings—it's simple and lightweight.
- Use Redis (or another distributed cache) if you need cross-instance support, can't modify app pool settings, or want maximum reliability for 48-hour caching.
内容的提问来源于stack exchange,提问作者Mohamed Sahir

