Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created November 18, 2020 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/b4d9fa57d9e6c2a546bdb11f03290f78 to your computer and use it in GitHub Desktop.
Save dcomartin/b4d9fa57d9e6c2a546bdb11f03290f78 to your computer and use it in GitHub Desktop.
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