场景:安装redis,并配置运行项目
报错信息:
Invalid input of type: 'CacheKey'. Convert to a byte, string or number first.
原因:redis版本过高
解决方法:
方法一:降低redis版本
pip install redis==2.10.6 # 之前版本是redis==3.2.1
方法二:重写redis
# 有时项目中必须使用redis==3.0版本,例如在我的项目中,celery4.3必须使用redis3.0以上的版本,所以不可能将redis降级,只能重写redis
首先,django中的settings.py中的CACHES必须去掉
# CACHES = {
# "default": {
# "BACKEND": "django_redis.cache.RedisCache",
# "LOCATION": "redis://127.0.0.1:6379/0",
# "OPTIONS": {
# "CLIENT_CLASS": "django_redis.client.DefaultClient",
# "CONNECTION_POOL_KWARGS": {"max_connections": 100} # 最大连接数
# }
# }
# }
# 如果需要配置redis,可以自己在settings.py中定义,我的配置如下(任意命名),不填配置,默认存到 127.0.0.1:6379/0
MY_CACHES_3 = {
"HOST":"127.0.0.1",
"PORT":6379,
"DB":0
}
新建文件(任意命名)
from redis import Redis
from django.conf import settings
class MyDjangoRedis3(Redis):
def get(self, name):
"""
重写get()方法,因为Redis类中的get()返回的是二进制数据,我需要的是str类型的数据
:param name: 键
:return: 值(str)
"""
value = self.execute_command('GET', name)
if not value:
return None
return str(value,encoding="utf8")
redis3 = MyDjangoRedis3(
host=settings.MY_CACHES_3["HOST"],
port=settings.MY_CACHES_3["PORT"],
db=settings.MY_CACHES_3["DB"],
)
# host = 'localhost', port = 6379,
# db = 0, password = None, socket_timeout = None,
# socket_connect_timeout = None,
# socket_keepalive = None, socket_keepalive_options = None,
# connection_pool = None, unix_socket_path = None,
# encoding = 'utf-8', encoding_errors = 'strict',
# charset = None, errors = None,
# decode_responses = False, retry_on_timeout = False,
# ssl = False, ssl_keyfile = None, ssl_certfile = None,
# ssl_cert_reqs = 'required', ssl_ca_certs = None,
# max_connections = None
使用
from xxx.xxx.xxx import redis3 # 找到文件中的实例化对象,即redis3 = MyDjangoRedis3()中的redis3
设置: redis3.set("key","value") # 和之前的调用一样 cache.set()
获取: redis3.get("key") # 和之前的调用一样 cache.get()
#2.2 未知错误
报错
zmalloc.h:50:31: fatal error: jemalloc/jemalloc.h: No such file or directory
原因
未知
解决
make MALLOC=libc
#2.3 未知错误
报错
输入make test后
报错You need tcl 8.5 or newer in order to run the Redis test
原因
未知
解决
yum install tcl
#2.4 redis.conf 不生效
问题
配置redis.conf 重启redis后,总是不生效
解决
redis.conf文档的前几行解释
# Redis configuration file example.
#
# Note that in order to read the configuration file, Redis must be
# started with the file path as first argument:
#
# ./redis-server /path/to/redis.conf
启动 ./redis-server 时,需要带上redis.conf
# 启动redis
./redis-server /path/to/redis.conf # 带上配置后的redis.conf