標籤:python redis
Redis 和Memcached類似 也是一個開源的記憶體儲存系統,儲存格式也是通過索引值對的方式。不過和memcached比起來,memcached的value只支援字串,而redis支援字串,列表,集合,hash等等;這些資料類型都支援push/pop,add/remove等操作,而且都是原子性的,也就是類似資料庫的事物特徵一樣,所有的操作要麼全部完成,要麼全部失敗,然後復原到之前的狀態。
現在來看看他的簡單使用和發布訂閱的功能。
伺服器安裝
[[email protected] ~]# wget http://download.redis.io/releases/redis-3.0.6.tar.gz [[email protected] ~]# tar xzf redis-3.0.6.tar.gz[[email protected] ~]# cd redis-3.0.6/[[email protected] redis-3.0.6]# make
裝好的介面如下,使用預設的設定檔,他的訪問連接埠是6379
make[1]: Leaving directory `/root/redis-3.0.6/src‘[[email protected] redis-3.0.6]# src/redis-server24344:C 07 Nov 10:40:21.763 # Warning: no config file specified, using the default confif24344:M 07 Nov 10:40:21.764 * Increased maximum number of open files to 10032 (it was or. _._ _.-``__ ‘‘-._ _.-`` `. `_. ‘‘-._ Redis 3.0.6 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ‘‘-._ ( ‘ , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|‘` _.-‘| Port: 6379 | `-._ `._ / _.-‘ | PID: 24344 `-._ `-._ `-./ _.-‘ _.-‘ |`-._`-._ `-.__.-‘ _.-‘_.-‘| | `-._`-._ _.-‘_.-‘ | http://redis.io `-._ `-._`-.__.-‘_.-‘ _.-‘ |`-._`-._ `-.__.-‘ _.-‘_.-‘| | `-._`-._ _.-‘_.-‘ | `-._ `-._`-.__.-‘_.-‘ _.-‘ `-._ `-.__.-‘ _.-‘ `-._ _.-‘ `-.__.-‘24344:M 07 Nov 10:40:21.766 # WARNING: The TCP backlog setting of 511 cannot be enforced.24344:M 07 Nov 10:40:21.766 # Server started, Redis version 3.0.624344:M 07 Nov 10:40:21.766 # WARNING overcommit_memory is set to 0! Background save may.24344:M 07 Nov 10:40:21.766 # WARNING you have Transparent Huge Pages (THP) support enab.24344:M 07 Nov 10:40:21.766 * The server is now ready to accept connections on port 6379
然後別忘記開啟防火牆連接埠
[[email protected] ~]# firewall-cmd --add-port=6379/tcp --permanentsuccess[[email protected] ~]# systemctl restart firewalld
接下來用同一個目錄下的用戶端程式測試一下,成功設定和擷取資料
[[email protected] redis-3.0.6]# src/redis-cli127.0.0.1:6379> set foo barOK127.0.0.1:6379> get foo"bar"127.0.0.1:6379>
現在看看Python下如何調用。
首先安裝redis模組
C:\WINDOWS\system32>pip install redisCollecting redis Using cached redis-2.10.5-py2.py3-none-any.whlInstalling collected packages: redisSuccessfully installed redis-2.10.5
第一個例子:
import redisr=redis.Redis(host=‘sydnagios‘,port=6379)r.set(‘name‘,‘John‘)print(r.get(‘name‘))-------b‘John‘
除了直接連接 也可以通過串連池串連,預設每個redis執行個體有自己的串連池,通過這種方式,可以多個執行個體共用一個串連池
import redispool=redis.ConnectionPool(host=‘sydnagios‘,port=6379)r=redis.Redis(connection_pool=pool)print(r.get(‘name‘))
redis和memcached比起來,因為他支援多種資料結構,因此對應的操作函數也很多,幾乎是memcached的10倍
下面是一些常見的,具體的函數使用可以參考 http://www.cnblogs.com/wupeiqi/articles/5132791.html
大量設定,批量擷取
pool=redis.ConnectionPool(host=‘sydnagios‘,port=6379)r=redis.Redis(connection_pool=pool)r.mset(name=‘kevin‘,age=14)print(r.mget(‘name‘,‘age‘))-----------[b‘kevin‘, b‘14‘]
自增
import redispool=redis.ConnectionPool(host=‘sydnagios‘,port=6379)r=redis.Redis(connection_pool=pool)r.incrby(‘age‘,10)print(r.get(‘age‘))-------b‘24‘
刪除
import redisr=redis.Redis(host=‘sydnagios‘,port=6379)r.delete(‘set1‘)
Hash大量操作
import redispool=redis.ConnectionPool(host=‘sydnagios‘,port=6379)r=redis.Redis(connection_pool=pool)r.hmset(‘computer‘,{‘Macbook‘:20000,‘Surface3‘:5000,‘iPhone7‘:9000})print(r.hmget(‘computer‘,‘Macbook‘))--------[b‘20000‘]
list操作
import redisr=redis.Redis(host=‘sydnagios‘,port=6379)r.lpush(‘list1‘,‘apple‘)r.lpush(‘list1‘,‘pear‘)print(r.llen(‘list1‘))print(r.lpop(‘list1‘))print(r.llen(‘list1‘))------2b‘pear‘1
set操作,集合的元素不可以重複
import redisr=redis.Redis(host=‘sydnagios‘,port=6379)r.sadd(‘set1‘,‘orange‘)r.sadd(‘set1‘,‘mango‘)print(r.scard(‘set1‘))print(r.smembers(‘set1‘))---------2{b‘mango‘, b‘orange‘}
管道
預設redis-py在執行一次操作請求的時候會自動連接,然後斷開;我們可以通過管道,一次性傳入多條操作然後執行。
# !/usr/bin/env python# -*- coding:utf-8 -*-import redispool = redis.ConnectionPool(host=‘sydnagios‘, port=6379)r = redis.Redis(connection_pool=pool)# pipe = r.pipeline(transaction=False)pipe = r.pipeline(transaction=True)r.set(‘name‘, ‘alex‘)r.set(‘age‘, 16)pipe.execute()
因為redis的函數實在太多 這裡就不一一贅述了。
現在來看一個redis的使用情境,發布和訂閱。
簡單的說,發行者可以對一個頻道發布資料,然後凡是訂閱了這個頻道的人都可以收到資訊。
s3.py
import redisclass RedisHelper: def __init__(self): self.__conn = redis.Redis(host=‘sydnagios‘) def publish(self, msg, chan): self.__conn.publish(chan, msg) return True def subscribe(self, chan): pub = self.__conn.pubsub() pub.subscribe(chan) pub.parse_response() return pub
s4.py(訂閱者)
import s3obj = s3.RedisHelper()data = obj.subscribe(‘fm111.7‘)print(data.parse_response())
s5.py(發行者)
import s3obj = s3.RedisHelper()obj.publish(‘alex db‘, ‘fm111.7‘)
先執行訂閱者的代碼,進入等待狀態,然後執行發行者的程式,對指定的channel發送資料‘alex db’,訂閱者一方會收到以下資料
[b‘message‘, b‘fm111.7‘, b‘alex db‘]
本文出自 “麻婆豆腐” 部落格,請務必保留此出處http://beanxyz.blog.51cto.com/5570417/1870139
Python 學習筆記 - Redis