This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<Product> GetProduct(Guid productId) | |
{ | |
// Step 1: Get Value from Cache | |
var cacheResult = await _cacheClient.GetAsync<Product>(BuildCacheKey(productId)); | |
if (cacheResult.HasValue) | |
{ | |
return cacheResult.Value; | |
} | |
// Step 2: Cache Miss, Fetch from Database | |
var product = await _dbContext.Products | |
.Where(x => x.Id == productId) | |
.Select(x => new Product | |
{ | |
Id = x.Id, | |
Name = x.Name, | |
}) | |
.SingleAsync(); | |
// Step 3 - Write to Cache & Expire in 30 minutes | |
await _cacheClient.SetAsync(BuildCacheKey(productId), product, DateTime.UtcNow.AddMinutes(30)); | |
return product; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment