tnblog
首页
视频
资源
登录

.NetCore 使用缓存

5436人阅读 2019/10/25 13:30 总访问:3212543 评论:0 收藏:1 手机
分类: .net后台框架

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





欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
这一世以无限游戏为使命!
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术