redis連接
安裝
pip install redis
簡單連接
import redis
# 直接連接redis
conn = redis.Redis(host='ip地址', port=6379, password='密碼', encoding='utf-8')
# 設置鍵值:aaa="9999" 且超時時間為10秒(值寫入到redis時會自動轉字符串)
conn.set('aaa', 9999, ex=10)
# 根據鍵獲取值:如果存在獲取值(獲取到的是字節類型);不存在則返回None
value = conn.get('aaa')
print(value)
上面python操作redis的示例是以直接創建連接的方式實現,每次操作redis如果都重新連接一次效率會比較低,建議使用redis連接池來替換,例如
連接池
import redis
# 創建redis連接池(默認連接池最大連接數 2**31=2147483648)
pool = redis.ConnectionPool(host='ip地址', port=6379, password='密碼', encoding='utf-8', max_connections=1000)
# 去連接池中獲取一個連接
conn = redis.Redis(connection_pool=pool)
# 設置鍵值:15131255089="9999" 且超時時間為10秒(值寫入到redis時會自動轉字符串)
conn.set('name', "小小", ex=10)
# 根據鍵獲取值:如果存在獲取值(獲取到的是字節類型);不存在則返回None
value = conn.get('name')
print(value)
django-redis
安裝
pip3 install django-redis
配置
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密碼", } } }
視圖中操作連接
from django_redis import get_redis_connection
conn = get_redis_connection() conn.set(phone, random_code, ex=30)