在ASP.NET Core 2.0中使用MemoryCache
来源:互联网 发布:众信旅游怎么样 知乎 编辑:程序博客网 时间:2024/05/29 04:54
说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在。今儿个就简单的聊聊如何在ASP.NET Core中使用内存缓存。我们一般将经常访问但是又不是经常改变的数据放进缓存是再好不过了,这样可以明显提高应用程序的性能。关于MemoryCache在Github上的地址:https://github.com/aspnet/Caching 总共有4个项目
第一个项目是缓存的抽象,其他三个是不同的类型Memory,Redis,SqServer
首先需要在ConfigureServices中注册缓存服务
public void ConfigureServices(IServiceCollection services){ services.AddMemoryCache(); services.AddMvc();}
在下面的代码中从Home控制器的构造函中获取IMemoryCache实例
public class HomeController : Controller{ private IMemoryCache _cache; public HomeController(IMemoryCache memoryCache) { _cache = memoryCache; }}
关于缓存的使用常用的就是Set Get Remove,有人喜欢把这些代码封装到单独的类库中,我觉得没有必要,它可以直接在我们的Web项目中直接使用,而且IMemory向外的提供的扩展方法就是最好的封装
设置缓存 Set
_cache.Set("key", "value");
获取缓存 Get
var result = _cache.GetOrCreate("myKey", (entry) =>{ entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120); return DateTime.Now.ToString();});
移除缓存 Remove
_cache.Remove("key");
原文地址:http://www.cnblogs.com/bidianqing/p/6954254.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
阅读全文
0 0
- 在ASP.NET Core 2.0中使用MemoryCache
- ASP.NET CORE CACHE的使用(含MemoryCache,Redis)
- 在ASP.NET Core 2.0中使用CookieAuthentication
- .NET Core 2.0迁移技巧之MemoryCache问题修复
- .NET Core 2.0迁移技巧之MemoryCache问题修复
- .NET Core 2.0迁移技巧之MemoryCache问题修复
- 在ASP.NET Core中使用百度在线编辑器UEditor
- 在ASP.NET Core中使用百度在线编辑器UEditor
- 在ASP.NET CORE 2.0使用SignalR技术
- 在.net core中使用AutoMapper
- 在离线环境中使用.NET Core
- 在.NET Core中使用MEF
- 在离线环境中使用.NET Core
- 在Visual Studio 2017中使用Asp.Net Core构建Angular4应用程序
- 在ASP.NET Core中使用Apworks开发数据服务:对HAL的支持
- 在ASP.NET Core中使用Apworks快速开发数据服务
- 在ASP.NET Core中使用Angular2,以及与Angular2的Token base身份认证
- 在ASP.NET Core中使用AOP来简化缓存操作
- .NET 传奇 1.0 的出版过程,以及未来计划
- Linux系统PWM驱动
- 深入探索.NET框架内部了解CLR如何创建运行时对象
- 在ASP.NET Core 2.0中使用CookieAuthentication
- 基于IntelliJ IDEA上创建Maven Spring MVC项目web.xml文件解读
- 在ASP.NET Core 2.0中使用MemoryCache
- 微软Azure开源开发者(深圳)峰会等你来
- .net core 集成 autofac
- IdentityServer4 SigningCredential(RSA 证书加密)
- Asp.Net Core 发布到IIS
- C# 7.2和8.0路线图
- IdentityServer4 指定角色授权(Authorize(Roles="admin"))
- 微软中国Azure开源开发者(深圳)研讨会
- 基于VS2017的Docker Support体检ASP.NET Core站点的Docker部署