-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlogPostController.cs
33 lines (27 loc) · 1.1 KB
/
BlogPostController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class BlogPostController : ControllerBase
{
private readonly IMemoryCache _memoryCache;
private readonly IBlogRepository _blogRepository;
private readonly CancellationTokenSource resetToken;
public BlogPostController(IMemoryCache memoryCache, IBlogRepository blogRepository)
{
_memoryCache = memoryCache;
_blogRepository = blogRepository;
resetToken = new CancellationTokenSource();
}
public async Task<IActionResult> GetBlogPost(int id)
{
// Cache key
var cacheKey = $"BlogPost_{id}";
// Check if the cache contains the blog post
if (!_memoryCache.TryGetValue(cacheKey, out BlogPost blogPost))
{
// Retrieve the blog post from the repository
blogPost = await _blogRepository.GetBlogPostByIdAsync(id);
var cacheEntryOptions = new MemoryCacheEntryOptions().AddExpirationToken(new CancellationChangeToken(resetToken.Token));
// Save the blog post in the cache
_memoryCache.Set(cacheKey, blogPost, cacheEntryOptions);
}
return Ok(blogPost);
}
}