【问题标题】:DistributedCache Expiry time based on server location基于服务器位置的 DistributedCache 到期时间
【发布时间】:2020-03-16 18:54:48
【问题描述】:

我有一个 ASP.NET Core 3.0 应用程序。在配置服务的 Startup.cs 中,我添加了以下行:

services.AddDistributedMemoryCache();

我正在使用分布式内存缓存来进行一些轻量级缓存。但是我确实对缓存到期有疑问 - 这是我在这种情况下在缓存中设置“Foo”5分钟的代码:

_cache.SetString(cacheKey, "Foo", new DistributedCacheEntryOptions() { AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(5) });

我的问题是关于我正在使用的 AbsoluteExpiration:

例如,如果我在伦敦有 2 台服务器,数据会在缓存中保存 5 分钟

如果我在芝加哥有两台服务器,数据会在缓存中保存 5 小时 5 分钟

如果我在伦敦和芝加哥有服务器,一个是 5 分钟,另一个是 5 小时,另一个是 5 分钟

*注意 - 为了简单起见,我假设前两个请求同时访问了网络场中的两台服务器,因此在两台服务器中都设置了缓存数据

我应该只使用DateTimeOffset.Now 而不是DateTimeOffset.UtcNow

【问题讨论】:

  • 使用 DateTimeOffset.UtcNow.
  • @WilliamXifaras - 你能解释一下为什么吗?

标签: c# .net asp.net-core caching


【解决方案1】:

如果您使用DateTimeOffset.NowDateTimeOffset.UtcNow 两者都可以,基本上非UTC 时间将转换为UTC,因为DateTimeOffset 包含UTC 偏移量。

所以没关系,微软让它变得非常简单。因为很容易将任何 DateTimeOffet 转换为 UTC。

早期用户设置的是 DateTime.Now 而不是 DateTime.UtcNow,这确实造成了混乱,DateTime.UtcNow 是正确的做法。

https://github.com/dotnet/corefx/blob/master/src/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs#L131

【讨论】:

    【解决方案2】:

    结束重写并使用以下内容:

                    var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(300));
    
                    _cache.SetString(cacheKey, "Foo", options);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2012-05-29
      • 2011-10-06
      • 1970-01-01
      相关资源
      最近更新 更多