










缓存通常用于提高数据访问的效率。一般来说,缓存读取和写入的逻辑遵循“先从缓存取,取不到再从数据库获取并写回缓存”的原则。为了避免多个线程同时修改缓存数据,我们需要加锁来保证数据一致性。
public class CacheService
{
private readonly ICache _cache;
private readonly IDatabase _database;
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public CacheService(ICache cache, IDatabase database)
{
_cache = cache;
_database = database;
}
public string GetDataFromCacheOrDb(string key)
{
// 1. 尝试从缓存获取数据
var data = _cache.Get(key);
if (data != null)
{
return data; // 缓存命中,直接返回
}
// 2. 如果缓存中没有,尝试加锁并获取数据
_semaphore.Wait();
try
{
// 再次检查缓存(可能另一个线程已经填充了缓存)
data = _cache.Get(key);
if (data != null)
{
return data; // 缓存命中,直接返回
}
// 3. 从数据库获取数据
data = _database.Query(key);
// 4. 将数据写入缓存
_cache.Set(key, data);
return data;
}
finally
{
// 释放锁
_semaphore.Release();
}
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。