注意: 这是一个详细的问题,询问如何使用 memcached 在我的 Web 应用程序中最好地实现和管理数据库缓存。这个问题使用 Python/Django 来说明数据模型和用法,但语言并不是那么相关。我真的对学习保持缓存一致性的最佳策略更感兴趣。Python/Django 恰好是我用来说明这个问题的语言。
我的申请规则:
- 我有一个 3 x 3 的整数单元格网格
- 这个网格的大小将来可能会增加或减少。我们的解决方案必须扩展。
- 它们是每行的累积分数,通过
(value * Y-Coord)
对该行中的每个单元格求和来计算。 - 它们是每列的累积分数,通过
(value * X-Coord)
对该列中的每个单元格求和来计算。 - 单元格中的值很少更改。但是这些值和分数分数经常被读取。
- 我想用它
memcached
来最小化我的数据库访问。 - 我想最小化/消除在我的数据库中存储重复或派生信息
下图显示了我的网格状态的示例。
我的代码:
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
class Cell(models.Model):
x = models.IntegerField(editable=False)
y = models.IntegerField(editable=False)
# Whenever this value is updated, the keys for the row and column need to be
# invalidated. But not sure exactly how I should manage that.
value = models.IntegerField()
class Row(models.Model):
y = models.IntegerField()
@property
def cummulative_score(self):
# I need to do some memcaching here.
# But not sure the smartest way to do it.
return sum(map(lambda p: p.x * p.value, Cell.objects.filter(y=self.y)))
class Column(models.Model):
x = models.IntegerField()
@property
def cummulative_score(self):
# I need to do some memcaching here.
# But not sure the smartest way to do it.
return sum(map(lambda p: p.y * p.value, Cell.objects.filter(x=self.x)))
所以这是我的问题:
你可以看到我已经设置了一个memcached
实例。当然我知道如何在memcached
. 但是鉴于我上面的代码,我应该如何正确命名键?如果键名是固定的,它将不起作用,因为每一行和每一列都必须存在单独的键。至关重要的是,当单元格中的值更新时,如何确保适当的键(并且只有适当的键)无效?
每当有人更新 Cell.values 以最小化数据库访问时,我如何管理缓存失效?没有一些 django 中间件可以为我处理这个簿记吗?我看到的文件没有这样做。