一些關於Redis的坑

Redis

#1 環境

Python3.7
django2.0.7

#2 遇到的問題

#2.1 redis在django項目中版本問題

報錯

Invalid input of type: 'CacheKey'. Convert to a byte, string or number first.

原因

redis的版本過高

當前redis==3.2.1

解決

方法一 : 降低redis版本

pip3 install redis==2.10.6

方法二 : 重寫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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章