尘叶心繁

.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; }
}




关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢