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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
[HttpGet("{key}")]
public async Task<IActionResult> Get(string key)
{
    var redis = _connectionMultiplexer.GetDatabase();
    var redisResponse = await redis.StringGetAsync(key);
    
    if(redisResponse.HasValue)
    {
        return Ok(redisResponse.ToString());
    }

    var dbResponse = await _keyAndValueContext.FindAsync<KeyAndValue>(key);
    await redis.StringSetAsync(key, dbResponse.Value); // optionally add the key to the Redis
    return Ok(dbResponse.Value);
    
}

Testing it out

There is an examples.rest 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.

1
2
3
4
5
GET http://localhost:5000/values/a 

###

GET http://localhost:5000/values/aa

Full source code available here

comments powered by Disqus

Related