Skip to main content
 首页 » 编程设计

python之如何使用派生数据在 Django 中进行 DB 内存缓存

2024年08月26日31freeliver54

注意: 这是一个详细的问题,询问如何使用 memcached 在我的 Web 应用程序中最好地实现和管理数据库缓存。这个问题使用 Python/Django 来说明数据模型和用法,但语言并不是那么相关。我真的更有兴趣了解保持缓存一致性的最佳策略是什么。 Python/Django 恰好是我用来说明这个问题的语言。

我的申请规则:

  1. 我有一个 3 x 3 的整数单元格
  2. 此网格的大小将来可能会增加或减少。我们的解决方案必须可扩展。
  3. 它们是每一行的累积分数,通过对该行中每个单元格的 (value * Y-Coord) 求和计算得出。
  4. 它们是每列的累积分数,通过对该列中每个单元格的 (value * X-Coord) 求和计算得出。
  5. 单元格中的值很少更改。但是那些值和分数分数被频繁读取。
  6. 我想使用 memcached 来尽量减少我的数据库访问。
  7. 我想尽量减少/消除在我的数据库中存储重复或派生的信息

下图显示了我的网格状态的示例。

我的代码:

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 中间件可以为我处理这个簿记吗? documents我见过的人不要那样做。

请您参考如下方法:

# your client, be it memcache or redis, assign to client variable 
# I think both of them use set without TTL for permanent values. 
 
class Cell(models.Model): 
    x = models.IntegerField(editable=False) 
    y = models.IntegerField(editable=False) 
    value = models.IntegerField() 
 
    def save(self, *args, **kwargs): 
        Cell.cache("row",self.y) 
        Cell.cache("column",self.x) 
        super(Cell, self).save(*args, **kwargs) 
 
    @staticmethod 
    def score(dimension, number): 
        return client.get(dimension+str(number), False) or Cell.cache(number) 
 
    @staticmethod 
    def cache(dimension, number): 
        if dimension == "row": 
            val = sum([c.y * c.value for c in Cell.objects.filter(y=number)]) 
            client.set(dimension+str(self.y),val) 
            return val 
 
        if dimension == "column": 
            val = sum([c.x * c.value for c in Cell.objects.filter(x=number)]) 
            client.set(dimension+str(self.x),val) 
            return val 
 
        raise Exception("No such dimension:"+str(dimension))