Requesting Data from two Data Stores in Sequence - Cache and a Database

Full source code available here

In the previous post, I showed how to query Redis and MS SQL in parallel, canceling the MS SQL request if Redis return a key. But that is not something you should do in a real application, the cache is there to take load off the database. Only query the database if the cache doesn’t have the data, then optionally add the data to the cache.

The code here is going to be identical to the previous post, except for the ValuesController. So I won’t repeat myself, see the previous post for NuGet packages, Startup.cs changes, seeding, and Docker Compose.

The Controller

See the previous post for the controller constructor.

Here is the updated Get method.

Lines 4-10 make the Redis query, and if a value is found, the controller returns it. If the key doesn’t exist in Redis, the database is queried and the key is added to Redis. Lines 12 and 13.

 2public async Task<IActionResult> Get(string key)
 4    var redis = _connectionMultiplexer.GetDatabase();
 5    var redisResponse = await redis.StringGetAsync(key);
 7    if(redisResponse.HasValue)
 8    {
 9        return Ok(redisResponse.ToString());
10    }
12    var dbResponse = await _keyAndValueContext.FindAsync<KeyAndValue>(key);
13    await redis.StringSetAsync(key, dbResponse.Value); // optionally add the key to the Redis
14    return Ok(dbResponse.Value);

Testing it out

There is an file in the source, with that, you can run queries from the REST Client extension for Visual Studio Code. The first request will find a key in Redis.

The second request will not find the key in Redis, it will hit the database then, and finally, the data will be added to Redis.

1GET http://localhost:5000/values/a 
5GET http://localhost:5000/values/aa

Full source code available here

comments powered by Disqus