Created
June 8, 2021 21:10
-
-
Save manoj-choudhari-git/4c8d96584beff520f5e90c67f022a8d1 to your computer and use it in GitHub Desktop.
.NET Core Web API - Demo showing Distributed SQL Cache usage
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
// Startup.cs to configure distributed memory cache. | |
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Specify ConnectionString, Schema and Table Name | |
services.AddDistributedSqlServerCache(options => | |
{ | |
options.ConnectionString = Configuration.GetConnectionString("CacheDbConnection"); | |
options.SchemaName = "dbo"; | |
options.TableName = "CacheStore"; | |
}); | |
services.AddControllers(); | |
} | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
// Some code... | |
} | |
} | |
// WeatherForecastController.cs - Showing usage of cache | |
[ApiController] | |
[Route("[controller]")] | |
public class WeatherForecastController : ControllerBase | |
{ | |
private static readonly string[] Summaries = new[] | |
{ | |
"Freezing", "Bracing", "Chilly", "Cool", | |
"Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" | |
}; | |
private readonly ILogger<WeatherForecastController> _logger; | |
private readonly IDistributedCache _distributedCache; | |
private readonly string WeatherForecastKey = "WeatherForecast"; | |
public WeatherForecastController(ILogger<WeatherForecastController> logger, IDistributedCache distributedCache) | |
{ | |
_logger = logger; | |
_distributedCache = distributedCache; | |
} | |
[HttpGet] | |
public async Task<IEnumerable<WeatherForecast>> Get() | |
{ | |
// Find cached item | |
byte[] objectFromCache = await _distributedCache.GetAsync(WeatherForecastKey); | |
if (objectFromCache != null) | |
{ | |
// Deserialize it | |
var jsonToDeserialize = System.Text.Encoding.UTF8.GetString(objectFromCache); | |
var cachedResult = JsonSerializer.Deserialize<IEnumerable<WeatherForecast>>(jsonToDeserialize); | |
if (cachedResult != null) | |
{ | |
// If found, then return it | |
return cachedResult; | |
} | |
} | |
// If not found, then recalculate response | |
var result = GenerateResponse(); | |
// Serialize the response | |
byte[] objectToCache = JsonSerializer.SerializeToUtf8Bytes(result); | |
var cacheEntryOptions = new DistributedCacheEntryOptions() | |
.SetSlidingExpiration(TimeSpan.FromSeconds(10)) | |
.SetAbsoluteExpiration(TimeSpan.FromSeconds(30)); | |
// Cache it | |
await _distributedCache.SetAsync(WeatherForecastKey, objectToCache, cacheEntryOptions); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment