.NetCore 使用缓存
电脑版发表于:2019/10/25 13:30
1.Startup.cs
services.AddMemoryCache(); services.AddMvc();
2.封装Logger类
[Route("api/todo")] [Authorize] public class ToDoController : Controller { private readonly List<ToDo> _toDo; private const string Key="TODO_KEY"; private readonly IMemoryCache _memoryCache; public ToDoController(IMemoryCache memoryCache) { _memoryCache = memoryCache; _toDo = new List<ToDo>() { new ToDo{ Id=Guid.NewGuid(), Title="吃饭", Completed=true }, new ToDo{ Id=Guid.NewGuid(), Title="学习c#", Completed=false }, new ToDo{ Id=Guid.NewGuid(), Title="学习EF", Completed=false }, }; if (!memoryCache.TryGetValue(Key,out List<ToDo> todos)) { var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(1)); _memoryCache.Set(Key, todos, options); } } [HttpGet] public IActionResult Get() { if (!_memoryCache.TryGetValue(Key, out List<ToDo> todos)) { todos = _toDo; var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(1)); _memoryCache.Set(Key, todos, options); } return Ok(todos); } [HttpPost] public IActionResult Post([FromBody]ToDoEdit toDoEdit) { var todo = new ToDo() { Id = Guid.NewGuid(), Title = toDoEdit.Title, Completed = toDoEdit.Completed }; if (!_memoryCache.TryGetValue(Key, out List<ToDo> todos)) { todos = _toDo; } todos.Add(todo); var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(1)); _memoryCache.Set(Key, todos, options); return Ok(todo); } }
3.Model
public class ToDo { public Guid Id { get; set; } public string Title { get; set; } public bool Completed { get; set; } }
public class ToDoEdit { public string Title { get; set; } public bool Completed { get; set; } }