在Redis缓存中存储多个版本的数据 [英] Store multiple versions of data in Redis cache

查看:70
本文介绍了在Redis缓存中存储多个版本的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些产品数据,需要在Redis缓存中存储多个版本.数据是JSON序列化的.获取纯(基本)数据的过程很昂贵,将其自定义为不同版本的过程也很昂贵,因此我想缓存所有版本以尽可能进行优化.假设自定义是基于单个参数的,我可以将该参数用作缓存键的一部分.

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似乎没有提供使用通配符使多个密钥失效的功能,并且在查看了Redis模式之后,我不确定我是否采用了正确的方法.

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.

是否有更好的方法可以在Redis中缓存此类自定义的半分层数据,使其可以过期?

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

推荐答案

Redis'Hash可以很好地满足您的需求.您可以将每个产品的版本存储为该产品的哈希键中的字段值.例如:

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}"

获取版本只是使用产品密钥和相关代码调用 HGET 场地.要使其失效,请 DEL 和/或

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

这篇关于在Redis缓存中存储多个版本的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆