項目之前使用memcache做緩存,現在轉到redis,改寫幾個語句的事情,然后就這種我把django-redis和py-redis搞混了,記錄一下。
django默認使用memcache做緩存,這里的操作一般是cache.get() cache.set()這種,要想操作使用from django.core.cache import cache就可以了。
具體安裝及操作見:http://blog.beginman.cn/blog/83/ (好像跑題了啊喂)
django現在可以使用redis做緩存,但是使用cache默認不能操作redis,這個時候就出現了django-redis了,一個開源的。
這個是要安裝的,然后配置就可以使用了,但是據說性能不夠高,官方文檔見https://niwinz.github.io/django-redis/latest/
而py-redis是一個python的庫,用來操作redis,效率已經不錯了,操作也比較簡單。
類似與import redis r.set() r.get() r.lpush() r.lpop() 這種操作。
文檔見:https://github.com/andymccurdy/redis-py
r.rpop() r.rpush()
示例:
In [2]: import redis In [3]: r = redis.StrictRedis(host='localhost', port=6379, db=0) In [4]: r.set('a', 'abc') Out[4]: True In [5]: r.get('a') Out[5]: 'abc' In [6]: r.get('b') In [7]: r.setex('b', 30, 'bcd') # 設置過期時間,第一次讀在30s內,有結果,第二次過了30s就沒有內容了 Out[7]: True In [8]: r.get('b') Out[8]: 'bcd' In [9]: r.get('b') In [10]: r.lpush('l', 1) Out[10]: 1L In [11]: r.lpop('l') Out[11]: '1' In [12]: r.llen() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-e38b57a801ea> in <module>() ----> 1 r.llen() TypeError: llen() takes exactly 2 arguments (1 given) In [13]: r.llen('l') Out[13]: 0 In [14]:
In [20]: r.delete('a') Out[20]: 1 In [21]: r.get('a')
In [22]: r.exists('a') Out[22]: False
In [23]: pipline = r.pipeline() In [24]: pipline.se pipline.sentinel pipline.sentinel_monitor pipline.sentinel_slaves pipline.setex pipline.sentinel_get_master_addr_by_name pipline.sentinel_remove pipline.set pipline.setnx pipline.sentinel_master pipline.sentinel_sentinels pipline.set_response_callback pipline.setrange pipline.sentinel_masters pipline.sentinel_set pipline.setbit In [24]: pipline.set('a', 'aaaaaaaaaaaaaaaa') Out[24]: StrictPipeline<ConnectionPool<Connection<host=127.0.0.1,port=6379,db=0>>> In [25]: pipline.set('b', 'bbbbbbbbbbbbbbbb') Out[25]: StrictPipeline<ConnectionPool<Connection<host=127.0.0.1,port=6379,db=0>>> In [26]: pipline.execu pipline.execute pipline.execute_command In [26]: pipline.execute() Out[26]: [True, True]
Pipelines are a subclass of the base Redis class that provide support for buffering multiple commands to the server in a single request. They can be used to dramatically increase the performance of groups of commands by reducing the number of back-and-forth TCP packets between the client and server.
參考見:
https://github.com/andymccurdy/redis-py
https://redis-py.readthedocs.io/en/latest/