Background
django 使用redis做缓存,或者是使用redis做channels layers backends。网上查到的大多都是无密码连接redis的配置,即使有密码的配置我也没试验通,最终摸索了好久才成功。这里贴出成功的配置,以及需要注意的地方。
redis cache
注释的非常清楚,这里就不赘述了。更具体详细配置请参考 django-redis官方文档
- 安装
pip install django-redis
- 配置
# Redis Cache
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://{}:{}/{}".format(redis_config.host, redis_config.port, redis_config.db),
"TIMEOUT": 60 * 60 * 24,
"OPTIONS": {
# 自动将byte转成字符串
"DECODE_RESPONSES": True,
"PASSWORD": redis_config.pwd,
# 连接池配置
"CONNECTION_POOL_KWARGS": {"max_connections": 100},
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# 开启压缩,默认不开始
"COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor",
},
"KEY_PREFIX": config.PROJECT + ":django",
},
}
# session backend
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
channel redis layers backends
- 这里的版本注意不要随意更换,安装顺序也不能变。
- 并且配置方式不要采用上面OPTIONS那种,除非你的redis密码中没有什么特殊符号。
- 安装
pip install channels-redis==2.4.2
pip uninstall channels
pip install channels~=3.0.4
- 配置
# channel layers backends
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [
"redis://:{}@{}:{}/{}".format(redis_config.pwd, redis_config.host, redis_config.port, redis_config.db)
],
},
}
}
- 存在的问题,但不影响使用
- channels版本必须使用3.0以上否则报错(错误2)
- channels-redis版本必须使用3.0以下否则报错(错误1)。
- 安装channels-redis会卸载channels,然后装一个兼容的版本,但是不能用。
- 所以需要先安装channels-redis,然后安装channels,然后会提示下面的版本不兼容错误(错误1),不用管就行了。
- 或者有人知道如何解决指教下哈。
# 错误1
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
channels-redis 2.4.2 requires channels~=2.2, but you have channels 3.0.4 which is incompatible.
# 错误2
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "E:\yl_pms\yl_pms\asgi.py", line 18, in <module>
from pms import routing
File "E:\yl_pms\pms\routing.py", line 6, in <module>
path('ws/log/', consumers.LogConsumer.as_asgi()),
AttributeError: type object 'LogConsumer' has no attribute 'as_asgi'