下载地址:点击打开链接
1、py-redis 其实就是redis-server的连接器
import redis
r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)
result = r.get("busy")
print(result)
2、django-redis 可以设置过期时间等,比py-redis 功能强大,显示的区别如下,:1:为django-redis添加的key:
setting添加:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': '127.0.0.1:6379',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
},
}
from django.core.cache import cache
def addCache(request):
#cache.set("busy", "hahahahhh", timeout=60*60)
value = cache.get("busy")
print(cache.ttl("busy"))
if value == None:
data = None
return HttpResponse(json.dumps(data), content_type="application/json")
else:
return HttpResponse(json.dumps(value), content_type="application/json")
无过期时间数据:
>>> cache.set("foo", "bar", timeout=22)
>>> cache.ttl("foo")
22
>>> cache.persist("foo")
>>> cache.ttl("foo")
None
锁:
with cache.lock("somekey"):
do_some_thing()
搜索:
>>> cache.keys("foo_*")
["foo_1", "foo_2"]
索引:
>>> cache.iter_keys("foo_*")
>>> next(cache.iter_keys("foo_*"))
"foo_1"
过滤删除:
>>> cache.delete_pattern("foo_*")
不存在则创建:
>>> cache.set("key", "value1", nx=True)
True
>>> cache.set("key", "value2", nx=True)
False
>>> cache.get("key")
"value1"
redis 原始接口,跟py-redis就一样了:
from django_redis import get_redis_connection
con = get_redis_connection("default")
value = con.get("busy")
配置最大连接数,获取当前连接数:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
...
"OPTIONS": {
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
}
}
}
from django.core.cache import get_cache
from django_redis import get_redis_connection
r = get_redis_connection("default") # Use the name you have defined for Redis in settings.CACHES
connection_pool = r.connection_pool
print("Created connections so far: %d" % connection_pool._created_connections)
其他配置建官网:
http://niwinz.github.io/django-redis/latest/#_why_use_django_redis