asp.net core 缓存使用
2022/2/9 20:18:44
本文主要是介绍asp.net core 缓存使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
// 在program.cs中加入这句,加入缓存支持 builder.Services.AddMemoryCache();
public class Book { public int Id { get; init; } public string Title { get; init; } public Book(int id, string title) { Id = id; Title = title; } public override string ToString() { return $"book:{Id}, {Title}"; } } public class BookDbContext { public Task<Book?> GetBookByIdAsync(int id) { Book? book = null; switch (id) { case 1: book = new Book(1, "book1"); break; case 2: book = new Book(2, "book2"); break; case 3: book = new Book(3, "book3"); break; } return Task.FromResult(book); } }
[ApiController] [Route("api/[controller]")] public class CacheTestController : ControllerBase { private IMemoryCache MemoryCache { get; init; } private ILogger<CacheTestController> Logger { get; set; } public CacheTestController(IMemoryCache memoryCache, ILogger<CacheTestController> logger) { MemoryCache = memoryCache; Logger = logger; } [HttpGet("book")] public async Task<ActionResult<Book?>> GetBookById(int id) { Logger.LogInformation($"enter GetBookById, id={id}"); // 尽量使用GetOrCreateAsync,而不是Get/Set。 // 因为GetOrCreateAsync可以把null也作为缓存值,这样就可以避免缓存穿透。 Book? book = await MemoryCache.GetOrCreateAsync($"book_{id}", (e) => { Logger.LogInformation($"not found in cache, search in BookDbContext."); // 混用SlidingExpiration和AbsoluteExpirationRelativeToNow,这样滑动超时或绝对超时后,缓存都会失效, e.SlidingExpiration = TimeSpan.FromSeconds(5); // 使用随机数作为超时值,避免缓存雪崩 e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Random.Shared.Next(10, 50)); return new BookDbContext().GetBookByIdAsync(id); }); Logger.LogInformation($"GetOrCreateAsync returns {book}"); if (book == null) return NotFound($"cannot find bood with id:{id}"); return book; } [ResponseCache(Duration = 10)] // 浏览器缓存支持,在响应头里加入cache-control: public,max-age=10 [HttpGet("Now")] public DateTime Now() { return DateTime.Now; } }
这篇关于asp.net core 缓存使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#