1. 程式人生 > >ASP.NET Core中使用EasyCaching作為緩存抽象層

ASP.NET Core中使用EasyCaching作為緩存抽象層

.get ogg evel 統一 exc ets tar pro eth

⒈是什麽?

和CacheManager差不多,兩者的定位和功能都差不多。

EasyCaching主要提供了下面的幾個功能

  1. 統一的抽象緩存接口
  2. 多種常用的緩存Provider(InMemory,Redis,Memcached,SQLite)
  3. 為分布式緩存的數據序列化提供了多種選擇
  4. 二級緩存
  5. 緩存的AOP操作(able, put,evict)
  6. 多實例支持
  7. 支持Diagnostics
  8. Redis的特殊Provider

⒉示例(以InMemory為例)

  1.安裝Nuget包

    EasyCaching.InMemory

  2.在Startup中配置服務及請求管道

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using EasyCaching.Core;
 6 using EasyCaching.InMemory;
 7 using Microsoft.AspNetCore.Builder;
 8 using Microsoft.AspNetCore.Hosting;
 9 using Microsoft.AspNetCore.Http;
10 using
Microsoft.AspNetCore.Mvc; 11 using Microsoft.Extensions.Configuration; 12 using Microsoft.Extensions.DependencyInjection; 13 14 namespace Coreqi.EasyCaching 15 { 16 public class Startup 17 { 18 public Startup(IConfiguration configuration) 19 { 20 Configuration = configuration;
21 } 22 23 public IConfiguration Configuration { get; } 24 25 // This method gets called by the runtime. Use this method to add services to the container. 26 public void ConfigureServices(IServiceCollection services) 27 { 28 services.AddEasyCaching(option => 29 { 30 // 使用InMemory最簡單的配置 31 option.UseInMemory("default"); 32 33 //// 使用InMemory自定義的配置 34 //option.UseInMemory(options => 35 //{ 36 // // DBConfig這個是每種Provider的特有配置 37 // options.DBConfig = new InMemoryCachingOptions 38 // { 39 // // InMemory的過期掃描頻率,默認值是60秒 40 // ExpirationScanFrequency = 60, 41 // // InMemory的最大緩存數量, 默認值是10000 42 // SizeLimit = 100 43 // }; 44 // // 預防緩存在同一時間全部失效,可以為每個key的過期時間添加一個隨機的秒數,默認值是120秒 45 // options.MaxRdSecond = 120; 46 // // 是否開啟日誌,默認值是false 47 // options.EnableLogging = false; 48 // // 互斥鎖的存活時間, 默認值是5000毫秒 49 // options.LockMs = 5000; 50 // // 沒有獲取到互斥鎖時的休眠時間,默認值是300毫秒 51 // options.SleepMs = 300; 52 // }, "m2"); 53 54 //// 讀取配置文件 55 //option.UseInMemory(Configuration, "m3"); 56 }); 57 58 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 59 } 60 61 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 62 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 63 { 64 if (env.IsDevelopment()) 65 { 66 app.UseDeveloperExceptionPage(); 67 } 68 else 69 { 70 app.UseExceptionHandler("/Home/Error"); 71 } 72 73 app.UseStaticFiles(); 74 app.UseCookiePolicy(); 75 76 // 如果使用的是Memcached或SQLite,還需要下面這個做一些初始化的操作 77 app.UseEasyCaching(); 78 79 80 app.UseMvc(routes => 81 { 82 routes.MapRoute( 83 name: "default", 84 template: "{controller=Home}/{action=Index}/{id?}"); 85 }); 86 } 87 } 88 }

  3.創建一個實體類

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace Coreqi.EasyCaching.Models
 7 {
 8     public class User
 9     {
10         public int id { get; set; }
11         public string username { get; set; }
12         public string password { get; set; }
13         public int enabled { get; set; }
14     }
15 }

  4.模擬一個服務層

 1 using Coreqi.EasyCaching.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 
 7 namespace Coreqi.EasyCaching.Services
 8 {
 9     public class UserService
10     {
11         public static IList<User> users;
12         public UserService()
13         {
14             users = new List<User>
15             {
16                 new User{ id = 1,username = "fanqi",password = "admin",enabled = 1},
17                 new User{ id = 2,username = "gaoxing",password = "admin",enabled = 1}
18             };
19         }
20         public IList<User> getAll()
21         {
22             return users;
23         }
24         public User getById(int id)
25         {
26             return users.FirstOrDefault(f => f.id == id);
27         }
28         public User add(User user)
29         {
30             users.Add(user);
31             return user;
32         }
33         public User modify(User user)
34         {
35             delete(user.id);
36             add(user);
37             return user;
38         }
39         public void delete(int id)
40         {
41             users.Remove(getById(id));
42         }
43     }
44 }

  5.控制器中使用緩存

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Coreqi.EasyCaching.Models;
 6 using Coreqi.EasyCaching.Services;
 7 using EasyCaching.Core;
 8 using Microsoft.AspNetCore.Mvc;
 9 
10 namespace Coreqi.EasyCaching.Controllers
11 {
12     [Route("api/[controller]")]
13     public class UserController : Controller
14     {
15         private readonly IEasyCachingProvider _cache;
16         private readonly UserService service = new UserService();
17         public UserController(IEasyCachingProvider cache)
18         {
19             this._cache = cache;
20         }
21         public IActionResult Index()
22         {
23             return View();
24         }
25 
26         [HttpGet]
27         [Route("add")]
28         public async Task<IActionResult> Add()
29         {
30             IList<User> users = service.getAll();
31             _cache.Set("users", users, TimeSpan.FromMinutes(2));
32             await _cache.SetAsync("users2", users, TimeSpan.FromMinutes(3));
33             return await Task.FromResult(new JsonResult(new { message = "添加成功!" }));
34         }
35 
36         [HttpGet]
37         [Route("remove")]
38         public async Task<IActionResult> Remove()
39         {
40             _cache.Remove("users");
41             await _cache.RemoveAsync("users2");
42             return await Task.FromResult(new JsonResult(new { message = "刪除成功!" }));
43         }
44 
45         [HttpGet]
46         [Route("get")]
47         public async Task<IActionResult> Get()
48         {
49             var users = _cache.Get<List<User>>("users");
50             var users2 = await _cache.GetAsync<List<User>>("users2");
51             return await Task.FromResult(new JsonResult(new { users1 = users.Value,users2 = users2.Value }));
52         }
53     }
54 }

ASP.NET Core中使用EasyCaching作為緩存抽象層