django-redis 和 py-redis

下载地址:点击打开链接

 

1、py-redis 其实就是redis-server的连接器

 

  1. import redis  
  2.   
  3. r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)  
  4.   
  5. result = r.get("busy")  
  6.   
  7. print(result)  



2、django-redis 可以设置过期时间等,比py-redis 功能强大,显示的区别如下,:1:为django-redis添加的key:

setting添加:

 

  1. CACHES = {  
  2.     'default': {  
  3.         'BACKEND': 'django_redis.cache.RedisCache',  
  4.         'LOCATION': '127.0.0.1:6379',  
  5.         "OPTIONS": {  
  6.             "CLIENT_CLASS": "django_redis.client.DefaultClient",  
  7.         },  
  8.     },  
  9. }  


view中引用:

 

 

  1. from django.core.cache import cache  
  2.   
  3. def addCache(request):  
  4.     #cache.set("busy", "hahahahhh", timeout=60*60)  
  5.     value = cache.get("busy")  
  6.     print(cache.ttl("busy"))  
  7.     if value == None:  
  8.         data = None  
  9.         return HttpResponse(json.dumps(data), content_type="application/json")  
  10.     else:  
  11.         return HttpResponse(json.dumps(value), content_type="application/json")  

 

 

无过期时间数据:

 

  1. >>> cache.set("foo", "bar", timeout=22)  
  2. >>> cache.ttl("foo")  
  3. 22  
  4. >>> cache.persist("foo")  
  5. >>> cache.ttl("foo")  
  6. None  



 

锁:

 

  1. with cache.lock("somekey"):  
  2.     do_some_thing()  



 

搜索:

 

  1. >>> cache.keys("foo_*")  
  2. ["foo_1", "foo_2"]  



 

索引:

 

  1. >>> cache.iter_keys("foo_*")  
  2. <generator object algo at 0x7ffa9c2713a8>  
  3. >>> next(cache.iter_keys("foo_*"))  
  4. "foo_1"  



 

过滤删除:

 

  1. >>> cache.delete_pattern("foo_*")  



 

不存在则创建:

 

  1. >>> cache.set("key", "value1", nx=True)  
  2. True  
  3. >>> cache.set("key", "value2", nx=True)  
  4. False  
  5. >>> cache.get("key")  
  6. "value1"  



 

redis 原始接口,跟py-redis就一样了:

 

  1. from django_redis import get_redis_connection  
  2.   
  3. con = get_redis_connection("default")  
  4.     value = con.get("busy")  



 

配置最大连接数,获取当前连接数:

 

  1. CACHES = {  
  2.     "default": {  
  3.         "BACKEND": "django_redis.cache.RedisCache",  
  4.         ...  
  5.         "OPTIONS": {  
  6.             "CONNECTION_POOL_KWARGS": {"max_connections": 100}  
  7.         }  
  8.     }  
  9. }  
  10.   
  11.   
  12. from django.core.cache import get_cache  
  13. from django_redis import get_redis_connection  
  14.   
  15. r = get_redis_connection("default")  # Use the name you have defined for Redis in settings.CACHES  
  16. connection_pool = r.connection_pool  
  17. print("Created connections so far: %d" % connection_pool._created_connections)  



 

其他配置建官网:

http://niwinz.github.io/django-redis/latest/#_why_use_django_redis

posted @ 2018-01-12 23:34  alxe_yu  阅读(115)  评论(0)    收藏  举报