如何按预期使用MemoryCache触发旧缓存值的删除

本文关键字:缓存 删除 何按预 MemoryCache | 更新日期: 2023-09-27 18:14:15

我使用下面的代码,以确保我只去数据库一次我的代理数据和缓存的数据是引用contractId被传递在变化。

public static AgentCacher
{
    private IAgentDal AgentDal;
    private readonly ObjectCache AgentObjectCache;
    private string LastContractId;
    public AgentCacher(IAgentDal agentDal)
    {
        this.AgentDal = agentDal;
        // Get the instance of the cache
        this.AgentObjectCache = MemoryCache.Default;
    }
    public List<Agent> GetAgentsForContract(int contractId)
    {
        // Set the key to be used for the cache
        var cacheKey = contractId.ToString(CultureInfo.InvariantCulture);
        // Has the contract ID changed?
        if (this.LastContractId !== cacheKey)
        {
            // Remove the item from the cache
            this.AgentObjectCache.Remove(this.LastContractId);
        }
        // Are the agents for this contract ID already in the cache?
        else if (this.AgentObjectCache.Contains(cacheKey))
        {
            // Return agents list from the cache
            return
                this.AgentObjectCache.Get(cacheKey) as
                List<Agent>;
        }
        // Go to the database and get the agents
        var agentsFromDatabase = this.AgentDal.GetAgentsForContract(contractId);
        // Add the values to the cache
        this.AgentObjectCache.Add(cacheKey, agentsFromDatabase, DateTimeOffset.MaxValue);
        // Set the contract Id for checking next time
        this.LastContractId = cacheKey;
        // Return the agents
        return agentsFromDatabase;
    }
}

这工作得很好,但我觉得我可能没有按照预期的方式使用MemoryCache

我如何trigger删除我添加到缓存中的值以清除旧值当contractId变化时,我是否必须使用ChangeMonitorCacheItemPolicy,可以在添加到缓存时传递?

我一直在努力寻找如何正确使用它的例子。

如何按预期使用MemoryCache触发旧缓存值的删除

你的逻辑看起来是对的。然而,您自己管理缓存生命周期,而不是依赖于内置的过期系统技术。例如,不是你检查是否有一个新的合约,删除旧的并添加新的,我认为你应该缓存尽可能多的合约,但要有一个绝对过期1小时。例如,如果有contracactid == 1,那么你将拥有缓存键1的缓存,如果另一个请求请求contracactid == 2,那么你将去db拉id == 2的合约信息,并将其存储在缓存中,以等待另一个绝对过期1小时左右。我认为这将比你自己管理缓存(添加,删除)更有效。

在向缓存中添加和删除数据时,还需要考虑锁定数据,以消除竞争条件。

你可以找到一个很好的例子:

使用c#中的缓存

在。net 4.0中使用内存缓存