缓存 - 用django cache设置的redis key的名字前加的序号有什么意义?

【字号: 日期:2022-08-18浏览:14作者:雯心

问题描述

使用django自带的模块处理redis缓存时,设置好的key比如说时“banners”, 到了在redis的cli下看到name就变成了“:1:banners”,这是django的机制,还是redis的呢

from django.core.cache import cachedef get_queryset(self):key = 'banners'queryset = cache.get(key)if not queryset: queryset = Banner.objects.filter(valid=True) cache.set(key, queryset, 3600)return queryset

问题解答

回答1:

你自己在配置redis会选择redis的库,redis本身就分为几个库,看你配置是哪一个

回答2:

这个是django cache的机制, key由前缀,版本号,真正的key组成。django在升级或者代码重构的时候有用,可以判断key是那个版本号,从而进行兼容(其它欢迎补充)

1.首先看django redis client api的实现:

# https://github.com/niwinz/django-redis/blob/master/django_redis/client/default.pydef get(self, key, default=None, version=None, client=None): ''' Retrieve a value from the cache. Returns decoded value if key is found, the default if not. ''' if client is None:client = self.get_client(write=False) key = self.make_key(key, version=version) try:value = client.get(key) except _main_exceptions as e:raise ConnectionInterrupted(connection=client, parent=e) if value is None:return default return self.decode(value)... 中间省略代码 ...def make_key(self, key, version=None, prefix=None): if isinstance(key, CacheKey):return key if prefix is None:prefix = self._backend.key_prefix if version is None:version = self._backend.version return CacheKey(self._backend.key_func(key, prefix, version))

它使用了make_key这个函数制作新的key,至于真正的key是从_backend.key_func来的。

2.其次查看django cache backend实现

# https://github.com/django/django/blob/master/django/core/cache/backends/base.pydef default_key_func(key, key_prefix, version): ''' Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix’. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. ''' return ’%s:%s:%s’ % (key_prefix, version, key)def get_key_func(key_func): ''' Function to decide which key function to use. Defaults to ``default_key_func``. ''' if key_func is not None:if callable(key_func): return key_funcelse: return import_string(key_func) return default_key_func class BaseCache(object): def __init__(self, params): ... 中间省略代码 ...self.key_prefix = params.get(’KEY_PREFIX’, ’’)self.version = params.get(’VERSION’, 1)self.key_func = get_key_func(params.get(’KEY_FUNCTION’))

由此可见,django redis cache的key是有前缀,版本号,真正的key组成。

相关文章: