首页 技术 正文
技术 2022年11月17日
0 收藏 981 点赞 5,095 浏览 1524 个字

.NET Core支持多种不同的缓存,其中包括MemoryCache,它表示存储在Web服务器内存中的缓存; 

   内存中的缓存存储任何对象; 分布式缓存界面仅限于byte[]

1:在.net core中使用MemoryCache首先要下载MemoryCache包

在程序包管理器控制台输入命令:Install-Package Microsoft.Extensions.Caching.Memory 

     之后可以看到已经下载好了NuGet包“Microsoft.Extensions.Caching.Memory

使用IMemoryCache:内存中缓存是使用依赖注入从应用程序引用的服务,在Startup.cs中

 public void ConfigureServices(IServiceCollection services)
{
//使用依赖注入从应用程序引用服务
services.AddMemoryCache();
services.AddMvc();
}

IMemoryCache在构造函数中请求实例:

 //IMemoryCache在构造函数中请求实例
private IMemoryCache _cache;
// private object CacheKeys; public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
} public IActionResult Index()
{
DateTime cacheEntry;
string CacheKeys = "key";
// 使用TryGetValue来检测时间是否在缓存中
if (!_cache.TryGetValue(CacheKeys, out cacheEntry))
{
//时间未被缓存,添加一个新条目
cacheEntry = DateTime.Now; // 使用Set将其添加到缓存中
var cacheEntryOptions = new MemoryCacheEntryOptions()
// 在此期间保持高速缓存,如果被访问,则重新设置时间
.SetSlidingExpiration(TimeSpan.FromSeconds()); _cache.Set(cacheEntry, cacheEntry, cacheEntryOptions);
} return View("Index", cacheEntry);
}

显示当前时间:缓存的DateTime值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)

@model DateTime?<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" rel="external nofollow" >
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css" rel="external nofollow" ><div>
<h2>Actions</h2>
<ul>
<li><a asp-controller="Home" asp-action="CacheTryGetValueSet">TryGetValue and Set</a></li>
</ul>
</div><h3>Current Time: @DateTime.Now.TimeOfDay.ToString()</h3>
<h3>Cached Time: @(Model == null ? "No cached entry found" : Model.Value.TimeOfDay.ToString())</h3>

缓存的DateTime值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)。下图显示了从缓存中检索的当前时间和较早的时间:

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898