⒈是什么?
和CacheManager差不多,两者的定位和功能都差不多。
EasyCaching主要提供了下面的几个功能
- 统一的抽象缓存接口
- 多种常用的缓存Provider(InMemory,Redis,Memcached,SQLite)
- 为分布式缓存的数据序列化提供了多种选择
- 二级缓存
- 缓存的AOP操作(able, put,evict)
- 多实例支持
- 支持Diagnostics
- 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 [Serializable] 9 public class User 10 { 11 public int id { get; set; } 12 public string username { get; set; } 13 public string password { get; set; } 14 public int enabled { get; set; } 15 } 16 }
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 }
⒊改造为Redis示例
1.安装Nuget包
EasyCaching.Redis
2.在Startup中配置服务及请求管道
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.AddEasyCaching(option => 5 { 6 //使用redis 7 option.UseRedis(config => 8 { 9 config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); 10 },"localhostRedis"); 11 }); 12 13 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 14 }
3.启动程序
然后就发现数据缓存到Redis中了,不过,
对于序列化,都会有一个默认的实现是基于BinaryFormatter,因为这个不依赖于第三方的类库,如果没有指定其它的,就会使用这个去进行序列化的操作了。
除了这个默认的实现,还提供了三种额外的选择。Newtonsoft.Json,MessagePack和Protobuf。下面以在Redis的provider使用MessagePack为例,来看看它的用法。