In this article, we will learn how to use Azure Redis cache in ASP.NET Core.
Solution
Create a class library and add the following NuGet packages.
- StackExchange.Redis
- Newtonsoft.json
Add a class to encapsulate the settings.
- public AzureCacheSettings(string connectionString)
- {
- if (string.IsNullOrEmpty(connectionString))
- throw new ArgumentNullException("ConnectionString");
- this.ConnectionString = connectionString;
- }
- public string ConnectionString { get; }
- }
Add a class for cache storage. Add a constructor and private methods to initialize the Azure client.
- public AzureCacheStorage(AzureCacheSettings settings)
- {
- this.settings = settings;
- Init();
- }
- private AzureCacheSettings settings;
- private ConnectionMultiplexer connection;
- private IDatabase database;
- private IServer server;
- private void Init()
- {
- connection = ConnectionMultiplexer.Connect(settings.ConnectionString);
- database = connection.GetDatabase();
- server = connection.GetServer(connection.GetEndPoints().First());
- }
Now, add methods to access the cache.
- public async Task SetStringAsync(string key, string value)
- {
- await database.StringSetAsync(key, value);
- }
- public async Task SetObjectAsync(string key, object value)
- {
- await database.StringSetAsync(key, JsonConvert.SerializeObject(value));
- }
- public async Task<string> GetStringAsync(string key)
- {
- var value = await database.StringGetAsync(key);
- return value.IsNullOrEmpty ? "" : value.ToString();
- }
- public async Task<T> GetObjectAsync<T>(string key)
- {
- var value = await database.StringGetAsync(key);
- return value.IsNullOrEmpty ?
- ult(T) : JsonConvert.DeserializeObject<T>(value);
- }
- public async Task<bool> ExistAsync(string key)
- {
- return await database.KeyExistsAsync(key);
- }
- public async Task DeleteAsync(string key)
- {
- await database.KeyDeleteAsync(key);
- }
Inject and use the class.
- [Route("movies")]
- public class MoviesController : Controller
- {
- private readonly IAzureCacheStorage cacheStorage;
- public MoviesController(IAzureCacheStorage cacheStorage)
- {
- this.cacheStorage = cacheStorage;
- }
- [HttpGet]
- public async Task<IActionResult> Get()
- {
- var keys = this.cacheStorage.ListKeys();
- return Ok(keys);
- }
- [HttpGet("{id}", Name = "GetMovie")]
- public async Task<IActionResult> Get(string id)
- {
- var model = await this.cacheStorage.GetObjectAsync<Movie>(id);
- return Ok(model);
- }
- [HttpPost]
- public async Task<IActionResult> Create([FromBody]Movie model)
- {
- await this.cacheStorage.SetObjectAsync(model.Id.ToString(), model);
- return CreatedAtRoute("GetMovie", new { id = model.Id }, model);
- }
- [HttpDelete("{id}")]
- public async Task<IActionResult> Delete(string id)
- {
- await this.cacheStorage.DeleteAsync(id);
- return NoContent();
- }
- }
In ASP.NET Core web application, configure the services.
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddScoped<IAzureCacheStorage>(factory =>
- {
- return new AzureCacheStorage(new AzureCacheSettings(
- connectionString: Configuration["Cache_ConnectionString"]));
- });
- services.AddMvc();
- }
Discussion
The sample code will require you to setup Azure account and Redis cache. Instructions for these can be found here.
Source Code
Join the conversation! Your thoughts help the community grow.