NetCore使用程序缓存Caching

原创 Laughing  2017-08-13 17:43  阅读 177 次 评论 0 条

NetCore提供的缓存组件

NetCore一共提供了三种缓存组件,分别是

  • Memory
  • Redis
  • SqlServer

这篇文章,我们主要学习第一种Memory Caching

添加Nuget包

万年不变的第一步,我们添加Nuget包 Microsoft.Extensions.Caching.Memory

添加服务

依然是在我们的startup.csConfigureServices方法中注册服务,services.AddMemoryCache();

使用

一下代码在HomeController.cs中简单演示了集中常见的使用

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Autofac;  
  7. using Autofac.Core;  
  8. using Autofac.Extensions.DependencyInjection;  
  9. using Microsoft.AspNetCore.Builder;  
  10. using Microsoft.AspNetCore.Hosting;  
  11. using Microsoft.AspNetCore.Hosting.Internal;  
  12. using Microsoft.Extensions.Configuration;  
  13. using Microsoft.Extensions.DependencyInjection;  
  14. using Microsoft.Extensions.Logging;  
  15. using Microsoft.AspNetCore.Http;  
  16. using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;  
  17. using Microsoft.AspNetCore.Mvc.ViewFeatures;  
  18. using Microsoft.AspNetCore.Server.Kestrel;  
  19. using Microsoft.AspNetCore.StaticFiles;  
  20. using Microsoft.EntityFrameworkCore;  
  21. using Microsoft.Extensions.FileProviders;  
  22. using NLog.Extensions.Logging;  
  23. using PersonLinkCore.WebUI.Entity;  
  24. using PersonLinkCore.WebUI.Extension;  
  25. using PersonLinkCore.WebUI.Middleware;  
  26. using PersonLinkCore.WebUI.Repository;  
  27. using PersonLinkCore.WebUI.Repository.IRepository;  
  28.   
  29. namespace PersonLinkCore.WebUI  
  30. {  
  31.     public class Startup  
  32.     {  
  33.         public Startup(IHostingEnvironment env)  
  34.         {  
  35.             var builder = new ConfigurationBuilder()  
  36.                 .AddInMemoryCollection()  
  37.                 .SetBasePath(env.ContentRootPath)  
  38.                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)  
  39.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  40.                 .AddEnvironmentVariables();  
  41.             Configuration = builder.Build();  
  42.             Console.WriteLine(Configuration["ConnectString:conn"]);  
  43.         }  
  44.   
  45.         public IConfigurationRoot Configuration { get; }  
  46.   
  47.         // This method gets called by the runtime. Use this method to add services to the container.  
  48.         public IServiceProvider ConfigureServices(IServiceCollection services)  
  49.         {  
  50.             // Add framework services.  
  51.             services.AddDistributedMemoryCache();  
  52.             services.AddMemoryCache();  
  53.             services.AddSession(options =>  
  54.             {  
  55.                 options.CookieName = ".PersonLinkCore.Session";  
  56.                 options.IdleTimeout = TimeSpan.FromSeconds(10);  
  57.             });  
  58.             services.AddMvc();  
  59.             var conn = Configuration.GetSection("ConnectString").GetSection("conn").Value;  
  60.             services.AddDbContext<SysOptionsDbContext>(options => options.UseSqlServer(conn));  
  61.             //services.AddScoped<ISysOptions, SysOptionsRepository>();  
  62.             services.AddDirectoryBrowser();  
  63.             var containerBuilder = new ContainerBuilder();  
  64.             containerBuilder.RegisterModule<DefaultModule>();  
  65.             containerBuilder.Populate(services);  
  66.             var container = containerBuilder.Build();  
  67.             return new AutofacServiceProvider(container);  
  68.         }  
  69.   
  70.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  71.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  72.         {  
  73.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  74.             loggerFactory.AddDebug();  
  75.             loggerFactory.AddNLog();  
  76.             loggerFactory.ConfigureNLog(Directory.GetCurrentDirectory() + @"/nlog.config");  
  77.             if (env.IsDevelopment())  
  78.             {  
  79.                 app.UseDeveloperExceptionPage();  
  80.                 app.UseBrowserLink();  
  81.             }  
  82.             else  
  83.             {  
  84.                 app.UseExceptionHandler("/Home/Error");  
  85.             }  
  86.               
  87.               
  88.             app.UseFileServer(new FileServerOptions()  
  89.             {  
  90.                 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"MyStaticFiles")),  
  91.                 RequestPath = new PathString("/StaticFiles"),  
  92.                 EnableDirectoryBrowsing = true,  
  93.                 DefaultFilesOptions    =  
  94.                 {  
  95.                     DefaultFileNames = new List<string>(){"Blog.html"}  
  96.                 },  
  97.                 EnableDefaultFiles = true  
  98.             });  
  99.               
  100.             FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();  
  101.             provider.Mappings[".myapp"] = "application/x-mswodnload";  
  102.             provider.Mappings[".html3"] = "application/html";  
  103.             app.UseStaticFiles(new StaticFileOptions()  
  104.             {  
  105.                 ContentTypeProvider = provider  
  106.             });  
  107.               
  108.             app.UseSession(new SessionOptions()  
  109.             {  
  110.                 IdleTimeout = new TimeSpan(20)  
  111.             });  
  112.               
  113.             app.UseMvc(routes =>  
  114.             {  
  115.                 routes.MapRoute(  
  116.                     name: "default",  
  117.                     template: "{controller=Home}/{action=Index}/{id?}");  
  118.             });  
  119.         }  
  120.     }  
  121. }  
本文地址:https://www.lisen.me/netcore-use-application-cache-caching.html
版权声明:本文为原创文章,版权归 木子网 所有,欢迎分享本文,转载请保留出处!

发表评论


表情