Store multiple versions of data in Redis cache

2019-07-07 15:01发布

问题:

I have some product data that I need to store multiple versions of in a Redis cache. The data is JSON-serialised. The process of obtaining the plain (basic) data is expensive, and the process of customising it into different versions is also expensive, so I'd like to cache all versions to optimise wherever possible. Let's say that the customisation is based on a single parameter, and I can use that parameter as part of the cache key.

The process I had planned to use to retrieve product data is something like this:

if cache contains appropriately customised data for this parameter
    return customised data from cache
else
    if cache contains basic data
        get basic data from cache
    else
        get basic data from primary data source (expensive)
        save basic data to cache for next time

apply customisations to basic data (expensive)
save customised version to cache, using the parameter as a key
return customised product

This all works well, but I'm now trying to work out the best way of invalidating the cache data when the underlying data source changes. If the basic product information changes, then all customised versions need to be expired as well. I will get notified when this needs to happen.

Note that the parameters used for customising the product are not easily enumerable. There are a large number of possible parameters, so iterating through all possible keys is not feasible.

Redis doesn't seem to provide an ability to expire multiple keys using a wildcard, and having looked around at Redis patterns, I'm not sure that I'm approaching this the right way.

Is there a better way to cache this sort of customised, semi-hierarchical data in Redis such that it can be expired?

回答1:

Redis' Hash would work well for your needs. You can store each product's version as the value of a field in a Hash key for that product. For example:

HSET id:14 1 "{your JSON data v1}"

Fetching a version is just calling HGET with the product's key and relevant field. To invalidate, DEL and/or EXPIRE the entire Hash.



标签: caching redis