1.啟動rabbimq、mysql
在“”執行“”裡輸入services.msc,找到rabbimq、mysql啟動即可
2.啟動redis
管理員進入cmd,進入redis所在目錄,執行redis-server.exe redis.windows.conf --maxmemory 200M 啟動redis server
執行redis-cli.exe啟動客戶端
一、 python系列之 RabbitMQ - hello world
介紹
import pika import sys username = 'wt' #rabbitmq使用者名稱 pwd = ' #rabbitmq密碼 user_pwd = pika.PlainCredentials(username, pwd) s_conn = pika.BlockingConnection(pika.ConnectionParameters('192.168.1.240', credentials=user_pwd)) chan = s_conn.channel() print('hello')
或者 :
- credentials = pika.PlainCredentials('guest', 'geust')
- #這裡可以連線遠端IP,請記得開啟遠端埠
- parameters = pika.ConnectionParameters('localhost',5672,'/',credentials)
- connection = pika.BlockingConnection(parameters)
- channel = connection.channel()

Queue(佇列):queue就是一個"郵箱"的簡稱,它存在於RabbitMQ內部。雖然訊息在RabbitMQ和你的應用之間傳輸,但他們只能儲存在一 個佇列(queue)裡面。佇列是不受任何限制的約束,你可以想存多少就存多少 - 它本質上是一個無限的緩衝區。

Consumer(消費者):類似一個接收者, 一個 Consumer 是一個等待接收訊息的程式,以下我們簡稱 “C"

Hello World

- 我們這裡講的RabbitMQ採用的是AMQP 0.9.1 ,一個開放的、通用的訊息協議,在不同的語言中有很多的不同的RabbitMQ客戶端,我們下面使用的是pika, 這個是RabbitMQ小組推薦的python客戶端
Sending:

- import pika
- s_connec = pika.BlockingConnection(pika.ConnectionParameters('loaclhost'))
- chan = s_connec.channel()
我們現在就建立了連線了,由於我們中介軟體在本機所以這裡的設定的是“localhost",如果我們想連線到一個不同的伺服器,只 需要簡單的將”localhost" 改為 伺服器的主機名或IP地址.
- chan.queue_declare(queue='hello')
到這點我們就可以傳送一個訊息了,我們的第一個訊息將正式包含一個字串“hello world",將這個訊息傳送到 ”hello“佇列 在RabbitMQ中,一個訊息不能直接傳送到一個佇列中,通常需要通過一個交換(exchange),我們在後面的部分將詳細講解 exchange ,現在所有我們需要知道的是如何利用一個空字串標識預設的exchange。這個一個特殊的exchange -- 它使我們能夠確切地指定訊息應該到哪個佇列去。 這裡需要在 routing_key 引數中指定傳送的佇列名:
- chan.basic_publish(exchange="",
- routing_key='hello',
- body="hello world")
- print(" [x] Sent 'Hello World!'")
在我們退出應用程式之前,我們需要確認網路緩衝區已經flush而且訊息已經確認傳送到了RabbitMQ中,我們可以使用下面的程式碼來關閉連線
- s_connec.close()
Receiving

- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
下一步和之前一樣也需要確認佇列是否存在,使用 queue_declare 建立一個佇列。 你可能會問為什麼還需要在建立一次佇列,我們在上面的程式碼中已經建立了一次了。因為我們不能確認佇列是否已經存在了,如果我們的服務端還未啟動,佇列也就沒有建立,這個時候客戶端啟動了,就找不到佇列。為了避免這個問題就需要在客戶端和服務端均建立一下,這樣就能保證無論是服務端還是客戶端先啟動佇列都存在
- channel.queue_declare(queue='hello')
- 可以在伺服器上通過執行以下命令檢視佇列資訊
- $ sudo rabbitmqctl list_queues
從佇列接收訊息要更復雜一些,它需要為佇列訂閱一個 callback 函式來進行接收。當我們接收一個訊息後,這個 callback 函式將會被 pika函式庫自動呼叫, 在我們的這個例項裡面這個函式將用來列印接收的訊息內容到螢幕
- def callback(ch, method, properties, body):
- print(" [x] Received %r" % body)
下一步我們需要告訴RabbitMQ這個特殊的 callback 函式需要從我們的hello佇列接收訊息
- channel.basic_consume(callback,
- queue='hello',
- no_ack=True)
no_ack 引數將在後面的部分講解
- print(' [*] Waiting for messages. To exit press CTRL+C')
- channel.start_consuming()
完整程式碼:
- import pika
- connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
- channel = connection.channel()
- channel.queue_declare(queue='hello')
- channel.basic_publish(exchange='',
- routing_key='hello',
- body='Hello World!')
- print(" [x] Sent 'Hello World!'")
- connection.close()

Consumer:receive.py
- import pika
- def callback(ch, method, properties, body):
- print(" [x] Received %r" % body)
- connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
- channel = connection.channel()
- channel.queue_declare(queue='hello')
- channel.basic_consume(callback,
- queue='hello',
- no_ack=True)
- print(' [*] Waiting for messages. To exit press CTRL+C')
- channel.start_consuming()
二、python系列之 RabbitMQ - work queues

預備
- import pika
- import sys
- message = ' '.join(sys.argv[1:]) or "Hello World"
- channel.basic_publish(exchange='',
- routing_key='worker',
- body=message,
- properties=pika.BasicProperties(delivery_mode = 2,)
- )
- print(" [x] Send %r " % message)
之前老的 receive.py 指令碼也需要一些改變,我們對處理模組 callback 函式進行一些修改:它假裝對訊息中的每個小數點需要1秒時間進行處理,它將會從訊息佇列中pop一個訊息然後執行任務,我們用 worker.py 來命名這個檔案
- import time
- def callback(ch, method, properties, body):
- print(" [x] Received %r" % body)
- time.sleep(body.count(b'.'))
- print(" [x] Done")
- ch.basic_ack(delivery_tag = method.delivery_tag)
迴圈排程(Round-robin dispatching)
- shell1$ python worker.py
- [*] Waiting for messages. To exit press CTRL+C
- shell2$ python worker.py
- [*] Waiting for messages. To exit press CTRL+C
再開啟一個終端,執行 new_task.py ,執行多個任務
- shell3$ python new_task.py First message.
- shell3$ python new_task.py Second message..
- shell3$ python new_task.py Third message...
- shell3$ python new_task.py Fourth message....
- shell3$ python new_task.py Fifth message.....
讓我們看看兩個worker端接收的訊息:
- shell1$ python worker.py
- [*] Waiting for messages. To exit press CTRL+C
- [x] Received 'First message.'
- [x] Received 'Third message...'
- [x] Received 'Fifth message.....'
- shell2$ python worker.py
- [*] Waiting for messages. To exit press CTRL+C
- [x] Received 'Second message..'
- [x] Received 'Fourth message....'
預設,RabbitMQ將迴圈的傳送每個訊息到下一個Consumer , 平均每個Consumer都會收到同樣數量的訊息。 這種分發訊息的方式成為 迴圈排程(round-robin)
- import pika
- import sys
- connec = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
- channel = connec.channel()
- channel.queue_declare(queue='worker')
- message = ' '.join(sys.argv[1:]) or "Hello World"
- channel.basic_publish(exchange='',
- routing_key='worker',
- body=message,
- properties=pika.BasicProperties(delivery_mode = 2,)
- )
- print(" [x] Send %r " % message)
worker.py
- import time
- import pika
- connect = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
- channel = connect.channel()
- channel.queue_declare('worker')
- def callback(ch, method, properties,body):
- print(" [x] Received %r" % body)
- time.sleep(body.count(b'.'))
- print(" [x] Done")
- ch.basic_ack(delivery_tag = method.delivery_tag)
- channel.basic_consume(callback,
- queue='worker',
- )
- channel.start_consuming()
訊息確認(Message acknowledgment)
執行一個任務能消耗幾秒. 你可能想知道當一個consumer在執行一個艱鉅任務或執行到一半是死掉了會發生什麼。就我們當前的程式碼而言,一旦RabbitMQ 的分發完訊息給 consumer後 就立即從記憶體中移除該訊息。這樣的話,如果一個worker剛啟動你就結束掉,那麼訊息就丟失了。那麼所有傳送給這個 worker 的還沒有處理完成的訊息也將丟失。
- def callback(ch, method, properties, body):
- print " [x] Received %r" % (body,)
- time.sleep( body.count('.') )
- print " [x] Done"
- ch.basic_ack(delivery_tag = method.delivery_tag)
- channel.basic_consume(callback,
- queue='hello')
使用這個程式碼我們能確保即使在程式執行中使用CTRL+C結束worker程序也不會有訊息丟失。之後當worker死掉之後所有未確認的訊息將會重新進行轉發。
- 忘了 acknowlegement
- 忘記設定basic_ack是一個經常犯也很容易犯的錯誤,但後果是很嚴重的。當客戶端退出後訊息將會重新轉發,但RabbitMQ會因為不能釋放那些沒有回覆的訊息而消耗越來越多的記憶體
- 為了除錯(debug)這種型別的錯誤,你可以使用 rabbitmqctl 列印 message_unacknowledged 欄位:
- $ sudo rabbitmqctl list_queues name messages_ready messages_unacknowledged
- Listing queues ...
- hello 0 0
- ...done
訊息持久化(Message durability)
我們已經學習了即使客戶端死掉了任務也不會丟失。但是如果RabbitMQ服務停止了的話,我們的任務還是會丟失。
- channel.queue_declare(queue='hello', durable=True
儘管此命令本身定義是正確的,但我們設定後還是不會工作。因為我們已經定義了個名為 hello ,但不是durable屬性的佇列。RabbitMQ不允許你重新定義一個已經存在、但屬性不同的queue。RabbitMQ 將會給定義這個屬性的程式返回一個錯誤。但這裡有一個快速的解決方法:讓我們定義個不同名稱的佇列,比如 task_queue:
- channel.queue_declare(queue='task_queue', durable=True)
這個 queue_declare 需要在 生產者(producer) 和消費方(consumer) 程式碼中都進行設定。
- channel.basic_publish(exchange='',
- routing_key="task_queue",
- body=message,
- properties=pika.BasicProperties(
- delivery_mode = 2, # make message persistent
- ))
訊息持久化的注意點
公平排程(Fair dispatch)

- channel.basic_qos(prefetch_count=1)
程式碼彙總
- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.queue_declare(queue='task_queue', durable=True) # 設定佇列為持久化的佇列
- message = ' '.join(sys.argv[1:]) or "Hello World!"
- channel.basic_publish(exchange='',
- routing_key='task_queue',
- body=message,
- properties=pika.BasicProperties(
- delivery_mode = 2, # 設定訊息為持久化的
- ))
- print(" [x] Sent %r" % message)
- connection.close()
new_task.py 指令碼
- #!/usr/bin/env python
- import pika
- import time
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.queue_declare(queue='task_queue', durable=True) # 設定佇列持久化
- print(' [*] Waiting for messages. To exit press CTRL+C')
- def callback(ch, method, properties, body):
- print(" [x] Received %r" % body)
- time.sleep(body.count(b'.'))
- print(" [x] Done")
- ch.basic_ack(delivery_tag = method.delivery_tag)
- channel.basic_qos(prefetch_count=1) # 訊息未處理完前不要傳送資訊的訊息
- channel.basic_consume(callback,
- queue='task_queue')
- channel.start_consuming()
二、 python系列之 RabbitMQ -- Publish/Subscribe
前面的部分我們建立了一個工作佇列(work queue). 設想是每個任務都能分發到一個worker,這一部分我們將會做一些完全不同的事情 -- 我們將會分發一個訊息到多個消費方(consumer),這種模式被譽為釋出/訂閱(publish/subscribe)模式
為了闡明這種模式,我們將要建立一個簡單的日誌系統,由兩部分程式組成 -- 第一部分將要釋出日誌訊息,第二部分接收並列印
在我們的日誌系統中每個接收程式(receiver)將接收訊息並複製訊息內容,這樣我們將會執行一個receiver 記錄日誌到磁碟;與此同時我們執行另一個receiver輸入日誌到螢幕檢視。
本質上,釋出日誌訊息將會廣播到所有的receivers
交換 (Exchanges)

- channel.exchange_declare(exchange='logs',
- type='fanout')
fanout exchange非常簡單,你從這個名字中就能猜出來,它將從Producer方收到的訊息廣播給所有他知道的receiver方。而這正是我們的logger記錄所需要的訊息。
- $ sudo rabbitmqctl list_exchanges
- Listing exchanges ...
- logs fanout
- amq.direct direct
- amq.topic topic
- amq.fanout fanout
- amq.headers headers
- ...done.
在這個列表中有一些amq.* exchange和預設的exchange,這些都是預設建立的,但是這些未必是你所需要的。
- channel.basic_publish(exchange='',
- routing_key='hello',
- body=message)
這個exchange引數就是這個exchange的名字. 空字串標識預設的或者匿名的exchange:如果存在routing_key, 訊息路由到routing_key指定的佇列中。
- channel.basic_publish(exchange='logs',
- routing_key='',
- body=message)
臨時佇列( Temporary queues )
你應該記得我們之前使用有一個特定名字的佇列( hello、task_queue). 設定佇列名對我們來說是至關重要的 --- 我們需要給消費方指定同樣的佇列名字。 要在生產者和消費者之間共享佇列,給佇列設定一個名字是非常重要的。
- result = channel.queue_declare()
這樣, result.method.queue 包含一個隨機的佇列名, 比如:看起來像 amq.gen-JzTY20BRgKO-HjmUJj0wLg.
- result = channel.queue_declare(exclusive=True)
繫結(Bindings)

- channel.queue_bind(exchange='logs',
- queue=result.method.queue)
現在logs exchange 將要傳送訊息到我們的佇列
- 你可以在Server端通過rabbitmqctl list_bindings命令檢視繫結資訊
彙總(Putting it all together)

- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='logs',
- type='fanout')
- message = ' '.join(sys.argv[1:]) or "info: Hello World!"
- channel.basic_publish(exchange='logs',
- routing_key='',
- body=message)
- print(" [x] Sent %r" % message)
- connection.close()
如你所見, 當建立連線之後我們定義了一個exchange名logs, 由於釋出一個訊息到一個不存在的exchange是禁止的,所以這一步是必須有的。
- import pika
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='logs',
- type='fanout')
- result = channel.queue_declare(exclusive=True) # 佇列斷開後自動刪除臨時佇列
- queue_name = result.method.queue # 佇列名採用服務端分配的臨時佇列
- channel.queue_bind(exchange='logs',
- queue=queue_name)
- print(' [*] Waiting for logs. To exit press CTRL+C')
- def callback(ch, method, properties, body):
- print(" [x] %r" % body)
- channel.basic_consume(callback,
- queue=queue_name,
- no_ack=True)
- channel.start_consuming()
- $ python receive_logs.py > logs_from_rabbit.log
如果你想在螢幕上檢視輸出的日誌,新開一個終端並執行:
- $ python receive_logs.py
當然,發出日誌資訊:
- $ python emit_log.py
使用 rabbitmqlctl list_bindings 你能驗證程式碼確實建立了你想要的binding和佇列。執行兩個 receive_logs.py 程式你可以看到:
- $ sudo rabbitmqctl list_bindings
- Listing bindings ...
- logs exchange amq.gen-JzTY20BRgKO-HjmUJj0wLg queue []
- logs exchange amq.gen-vso0PVvyiRIL2WoV3i48Yg queue []
- ...done.
這個結果的解釋非常直白: 從 logs exchange 出來的資料傳送服務端自動分配的到兩個佇列名中,這也是我們預期的。
遠端過程呼叫(Remote procedure call (RPC))
在第二課我們學習了怎樣使用 工作佇列(work queues) 來在多個workers之間分發需要消時的 任務
但是如果我們需要在遠端的伺服器上呼叫一個函式並獲取返回結果 我們需要怎麼做呢?well這是一個不一樣的故事。 這中模式通常被稱為遠端過程呼叫或RPC
在這一刻我們將要使用RabbitMQ來建立一個RPC系統:一個客戶端和一個可擴充套件的RPC服務。由於我們沒有任何耗時的任務值得分配,我們將要建立一個仿RPC服務並返回斐波納契數值
客戶端介面(Client interface)
- fibonacci_rpc = FibonacciRpcClient()
- result = fibonacci_rpc.call(4)
- print("fib(4) is %r" % result)
回撥佇列(callback queue)
- result = channel.queue_declare(exclusive=True)
- callback_queue = result.method.queue
- channel.basic_publish(exchange='',
- routing_key='rpc_queue',
- properties=pika.BasicProperties(
- reply_to = callback_queue,
- ),
- body=request)
關聯ID (Correlation ID)
概要(Summary)

整合
- #!/usr/bin/env python
- import pika
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.queue_declare(queue='rpc_queue')
- def fib(n):
- if n == 0:
- return 0
- elif n == 1:
- return 1
- else:
- return fib(n-1) + fib(n-2)
- def on_request(ch, method, props, body):
- n = int(body)
- print(" [.] fib(%s)" % n)
- response = fib(n)
- ch.basic_publish(exchange='',
- routing_key=props.reply_to,
- properties=pika.BasicProperties(correlation_id = \
- props.correlation_id),
- body=str(response))
- ch.basic_ack(delivery_tag = method.delivery_tag)
- channel.basic_qos(prefetch_count=1)
- channel.basic_consume(on_request, queue='rpc_queue')
- print(" [x] Awaiting RPC requests")
- channel.start_consuming()
- #!/usr/bin/env python
- import pika
- import uuid
- class FibonacciRpcClient(object):
- def __init__(self):
- self.connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- self.channel = self.connection.channel()
- result = self.channel.queue_declare(exclusive=True)
- self.callback_queue = result.method.queue
- self.channel.basic_consume(self.on_response, no_ack=True,
- queue=self.callback_queue)
- def on_response(self, ch, method, props, body):
- if self.corr_id == props.correlation_id:
- self.response = body
- def call(self, n):
- self.response = None
- self.corr_id = str(uuid.uuid4())
- self.channel.basic_publish(exchange='',
- routing_key='rpc_queue',
- properties=pika.BasicProperties(
- reply_to = self.callback_queue,
- correlation_id = self.corr_id,
- ),
- body=str(n))
- while self.response is None:
- self.connection.process_data_events()
- return int(self.response)
- fibonacci_rpc = FibonacciRpcClient()
- print(" [x] Requesting fib(30)")
- response = fibonacci_rpc.call(30)
- print(" [.] Got %r" % response)
- $ python rpc_server.py
- [x] Awaiting RPC requests
請求一個斐波那契數,執行客戶端
- $ python rpc_client.py
- [x] Requesting fib(30)
四、redis
2.在python中操作如下:
set(name, value, ex=None, px=None, nx=False, xx=False)
123456在Redis中設定值,預設,不存在則建立,存在則修改
引數:
ex,過期時間(秒)
px,過期時間(毫秒)
nx,如果設定為True,則只有name不存在時,當前set操作才執行
xx,如果設定為True,則只有name存在時,崗前set操作才執行
setnx(name, value)
1設定值,只有name不存在時,執行設定操作(新增)
setex(name, value, time)
123# 設定值
# 引數:
# time,過期時間(數字秒 或 timedelta物件)
psetex(name, time_ms, value)
123# 設定值
# 引數:
# time_ms,過期時間(數字毫秒 或 timedelta物件)
mset(*args, **kwargs)
12345批量設定值
如:
mset(k1=
'v1'
, k2=
'v2'
)
或
mget({
'k1'
:
'v1'
,
'k2'
:
'v2'
})
get(name)
1獲取值
mget(keys, *args)
12345批量獲取
如:
mget(
'ylr'
,
'wupeiqi'
)
或
r.mget([
'ylr'
,
'wupeiqi'
])
getset(name, value)
1設定新值並獲取原來的值
getrange(key, start, end)
123456# 獲取子序列(根據位元組獲取,非字元)
# 引數:
# name,Redis 的 name
# start,起始位置(位元組)
# end,結束位置(位元組)
# 如: "武沛齊" ,0-3表示 "武"
setrange(name, offset, value)
1234# 修改字串內容,從指定字串索引開始向後替換(新值太長時,則向後新增)
# 引數:
# offset,字串的索引,位元組(一個漢字三個位元組)
# value,要設定的值
setbit(name, offset, value)
123456789101112131415161718192021222324252627# 對name對應值的二進位制表示的位進行操作
# 引數:
# name,redis的name
# offset,位的索引(將值變換成二進位制後再進行索引)
# value,值只能是 1 或 0
# 注:如果在Redis中有一個對應: n1 = "foo",
那麼字串foo的二進位制表示為:
01100110
01101111
01101111
所以,如果執行 setbit(
'n1'
,
7
,
1
),則就會將第
7
位設定為
1
,
那麼最終二進位制則變成
01100111
01101111
01101111
,即:
"goo"
# 擴充套件,轉換二進位制表示:
# source = "武沛齊"
source
=
"foo"
for
i
in
source:
num
=
ord
(i)
bin
(num).replace(
'b'
,'')
特別的,如果source是漢字
"武沛齊"
怎麼辦?
答:對於utf
-
8
,每一個漢字佔
3
個位元組,那麼
"武沛齊"
則有
9
個位元組
對於漢字,
for
迴圈時候會按照 位元組 迭代,那麼在迭代時,將每一個位元組轉換 十進位制數,然後再將十進位制數轉換成二進位制
11100110
10101101
10100110
11100110
10110010
10011011
11101001
10111101
10010000
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
武 沛 齊
getbit(name, offset)
1# 獲取name對應的值的二進位制表示中的某位的值 (0或1)
bitcount(key, start=None, end=None)
12345# 獲取name對應的值的二進位制表示中 1 的個數
# 引數:
# key,Redis的name
# start,位起始位置
# end,位結束位置
bitop(operation, dest, *keys)
12345678910# 獲取多個值,並將值做位運算,將最後的結果儲存至新的name對應的值
# 引數:
# operation,AND(並) 、 OR(或) 、 NOT(非) 、 XOR(異或)
# dest, 新的Redis的name
# *keys,要查詢的Redis的name
# 如:
bitop(
"AND"
,
'new_name'
,
'n1'
,
'n2'
,
'n3'
)
# 獲取Redis中n1,n2,n3對應的值,然後講所有的值做位運算(求並集),然後將結果儲存 new_name 對應的值中
strlen(name)
1# 返回name對應值的位元組長度(一個漢字3個位元組)
incr(self, name, amount=1)
1234567# 自增 name對應的值,當name不存在時,則建立name=amount,否則,則自增。
# 引數:
# name,Redis的name
# amount,自增數(必須是整數)
# 注:同incrby
incrbyfloat(self, name, amount=1.0)
12345# 自增 name對應的值,當name不存在時,則建立name=amount,否則,則自增。
# 引數:
# name,Redis的name
# amount,自增數(浮點型)
decr(self, name, amount=1)
12345# 自減 name對應的值,當name不存在時,則建立name=amount,否則,則自減。
# 引數:
# name,Redis的name
# amount,自減數(整數)
append(key, value)
12345# 在redis name對應的值後面追加內容
# 引數:
key, redis的name
value, 要追加的字串
Hash操作,redis中Hash在記憶體中的儲存格式如下圖:
hset(name, key, value)
123456789# name對應的hash中設定一個鍵值對(不存在,則建立;否則,修改)
# 引數:
# name,redis的name
# key,name對應的hash中的key
# value,name對應的hash中的value
# 注:
# hsetnx(name, key, value),當name對應的hash中不存在當前key時則建立(相當於新增)
hmset(name, mapping)
12345678# 在name對應的hash中批量設定鍵值對
# 引數:
# name,redis的name
# mapping,字典,如:{'k1':'v1', 'k2': 'v2'}
# 如:
# r.hmset('xx', {'k1':'v1', 'k2': 'v2'})
hget(name,key)
1# 在name對應的hash中獲取根據key獲取value
hmget(name, keys, *args)
1234567891011# 在name對應的hash中獲取多個key的值
# 引數:
# name,reids對應的name
# keys,要獲取key集合,如:['k1', 'k2', 'k3']
# *args,要獲取的key,如:k1,k2,k3
# 如:
# r.mget('xx', ['k1', 'k2'])
# 或
# print r.hmget('xx', 'k1', 'k2')
hgetall(name)
1獲取name對應
hash
的所有鍵值
hlen(name)
1# 獲取name對應的hash中鍵值對的個數
hkeys(name)
1# 獲取name對應的hash中所有的key的值
hvals(name)
1# 獲取name對應的hash中所有的value的值
hexists(name, key)
1# 檢查name對應的hash是否存在當前傳入的key
hdel(name,*keys)
1# 將name對應的hash中指定key的鍵值對刪除
hincrby(name, key, amount=1)
12345# 自增name對應的hash中的指定key的值,不存在則建立key=amount
# 引數:
# name,redis中的name
# key, hash對應的key
# amount,自增數(整數)
hincrbyfloat(name, key, amount=1.0)
12345678# 自增name對應的hash中的指定key的值,不存在則建立key=amount
# 引數:
# name,redis中的name
# key, hash對應的key
# amount,自增數(浮點數)
# 自增name對應的hash中的指定key的值,不存在則建立key=amount
hscan(name, cursor=0, match=None, count=None)
12345678910111213# 增量式迭代獲取,對於資料大的資料非常有用,hscan可以實現分片的獲取資料,並非一次性將資料全部獲取完,從而放置記憶體被撐爆
# 引數:
# name,redis的name
# cursor,遊標(基於遊標分批取獲取資料)
# match,匹配指定key,預設None 表示所有的key
# count,每次分片最少獲取個數,預設None表示採用Redis的預設分片個數
# 如:
# 第一次:cursor1, data1 = r.hscan('xx', cursor=0, match=None, count=None)
# 第二次:cursor2, data1 = r.hscan('xx', cursor=cursor1, match=None, count=None)
# ...
# 直到返回值cursor的值為0時,表示資料已經通過分片獲取完畢
hscan_iter(name, match=None, count=None)
123456789# 利用yield封裝hscan建立生成器,實現分批去redis中獲取資料
# 引數:
# match,匹配指定key,預設None 表示所有的key
# count,每次分片最少獲取個數,預設None表示採用Redis的預設分片個數
# 如:
# for item in r.hscan_iter('xx'):
# print item
List操作,redis中的List在在記憶體中按照一個name對應一個List來儲存。如圖:
lpush(name,values)
12345678# 在name對應的list中新增元素,每個新的元素都新增到列表的最左邊
# 如:
# r.lpush('oo', 11,22,33)
# 儲存順序為: 33,22,11
# 擴充套件:
# rpush(name, values) 表示從右向左操作
lpushx(name,value)
1234# 在name對應的list中新增元素,只有name已經存在時,值新增到列表的最左邊
# 更多:
# rpushx(name, value) 表示從右向左操作
llen(name)
1# name對應的list元素的個數
linsert(name, where, refvalue, value))
1234567# 在name對應的列表的某一個值前或後插入一個新值
# 引數:
# name,redis的name
# where,BEFORE或AFTER
# refvalue,標杆值,即:在它前後插入資料
# value,要插入的資料
r.lset(name, index, value)
123456# 對name對應的list中的某一個索引位置重新賦值
# 引數:
# name,redis的name
# index,list的索引位置
# value,要設定的值
r.lrem(name, value, num)
12345678# 在name對應的list中刪除指定的值
# 引數:
# name,redis的name
# value,要刪除的值
# num, num=0,刪除列表中所有的指定值;
# num=2,從前到後,刪除2個;
# num=-2,從後向前,刪除2個
lpop(name)
1234# 在name對應的列表的左側獲取第一個元素並在列表中移除,返回值則是第一個元素
# 更多:
# rpop(name) 表示從右向左操作
lindex(name, index)
1在name對應的列表中根據索引獲取列表元素
lrange(name, start, end)
12345# 在name對應的列表分片獲取資料
# 引數:
# name,redis的name
# start,索引的起始位置
# end,索引結束位置
ltrim(name, start, end)
12345# 在name對應的列表中移除沒有在start-end索引之間的值
# 引數:
# name,redis的name
# start,索引的起始位置
# end,索引結束位置
rpoplpush(src, dst)
1234# 從一個列表取出最右邊的元素,同時將其新增至另一個列表的最左邊
# 引數:
# src,要取資料的列表的name
# dst,要新增資料的列表的name
blpop(keys, timeout)
12345678# 將多個列表排列,按照從左到右去pop對應列表的元素
# 引數:
# keys,redis的name的集合
# timeout,超時時間,當元素所有列表的元素獲取完之後,阻塞等待列表內有資料的時間(秒), 0 表示永遠阻塞
# 更多:
# r.brpop(keys, timeout),從右向左獲取資料
brpoplpush(src, dst, timeout=0)
123456# 從一個列表的右側移除一個元素並將其新增到另一個列表的左側
# 引數:
# src,取出並要移除元素的列表對應的name
# dst,要插入元素的列表對應的name
# timeout,當src對應的列表中沒有資料時,阻塞等待其有資料的超時時間(秒),0 表示永遠阻塞
自定義增量迭代
123456789101112131415161718# 由於redis類庫中沒有提供對列表元素的增量迭代,如果想要迴圈name對應的列表的所有元素,那麼就需要:
# 1、獲取name對應的所有列表
# 2、迴圈列表
# 但是,如果列表非常大,那麼就有可能在第一步時就將程式的內容撐爆,所有有必要自定義一個增量迭代的功能:
def
list_iter(name):
"""
自定義redis列表增量迭代
:param name: redis中的name,即:迭代name對應的列表
:return: yield 返回 列表元素
"""
list_count
=
r.llen(name)
for
index
in
xrange
(list_count):
yield
r.lindex(name, index)
# 使用
for
item
in
list_iter(
'pp'
):
item
Set操作,Set集合就是不允許重複的列表
sadd(name,values)
1# name對應的集合中新增元素
scard(name)
1獲取name對應的集合中元素個數
sdiff(keys, *args)
1在第一個name對應的集合中且不在其他name對應的集合的元素集合
sdiffstore(dest, keys, *args)
1# 獲取第一個name對應的集合中且不在其他name對應的集合,再將其新加入到dest對應的集合中
sinter(keys, *args)
1# 獲取多一個name對應集合的並集
sinterstore(dest, keys, *args)
1# 獲取多一個name對應集合的並集,再講其加入到dest對應的集合中
sismember(name, value)
1# 檢查value是否是name對應的集合的成員
smembers(name)
1# 獲取name對應的集合的所有成員
smove(src, dst, value)
1# 將某個成員從一個集合中移動到另外一個集合
spop(name)
1# 從集合的右側(尾部)移除一個成員,並將其返回
srandmember(name, numbers)
1# 從name對應的集合中隨機獲取 numbers 個元素
srem(name, values)
1# 在name對應的集合中刪除某些值
sunion(keys, *args)
1# 獲取多一個name對應的集合的並集
sunionstore(dest,keys, *args)
1# 獲取多一個name對應的集合的並集,並將結果儲存到dest對應的集合中
sscan(name, cursor=0, match=None, count=None)
sscan_iter(name, match=None, count=None)
1# 同字串的操作,用於增量迭代分批獲取元素,避免記憶體消耗太大
有序集合,在集合的基礎上,為每元素排序;元素的排序需要根據另外一個值來進行比較,所以,對於有序集合,每一個元素有兩個值,即:值和分數,分數專門用來做排序。
zadd(name, *args, **kwargs)
12345# 在name對應的有序集合中新增元素
# 如:
# zadd('zz', 'n1', 1, 'n2', 2)
# 或
# zadd('zz', n1=11, n2=22)
zcard(name)
1# 獲取name對應的有序集合元素的數量
zcount(name, min, max)
1# 獲取name對應的有序集合中分數 在 [min,max] 之間的個數
zincrby(name, value, amount)
1# 自增name對應的有序集合的 name 對應的分數
r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float)
123456789101112131415161718# 按照索引範圍獲取name對應的有序集合的元素
# 引數:
# name,redis的name
# start,有序集合索引起始位置(非分數)
# end,有序集合索引結束位置(非分數)
# desc,排序規則,預設按照分數從小到大排序
# withscores,是否獲取元素的分數,預設只獲取元素的值
# score_cast_func,對分數進行資料轉換的函式
# 更多:
# 從大到小排序
# zrevrange(name, start, end, withscores=False, score_cast_func=float)
# 按照分數範圍獲取name對應的有序集合的元素
# zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
# 從大到小排序
# zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=float)
zrank(name, value)
1234# 獲取某個值在 name對應的有序集合中的排行(從 0 開始)
# 更多:
# zrevrank(name, value),從大到小排序
zrangebylex(name, min, max, start=None, num=None)
1234567891011121314151617# 當有序集合的所有成員都具有相同的分值時,有序集合的元素會根據成員的 值 (lexicographical ordering)來進行排序,而這個命令則可以返回給定的有序集合鍵 key 中, 元素的值介於 min 和 max 之間的成員
# 對集合中的每個成員進行逐個位元組的對比(byte-by-byte compare), 並按照從低到高的順序, 返回排序後的集合成員。 如果兩個字串有一部分內容是相同的話, 那麼命令會認為較長的字串比較短的字串要大
# 引數:
# name,redis的name
# min,左區間(值)。 + 表示正無限; - 表示負無限; ( 表示開區間; [ 則表示閉區間
# min,右區間(值)
# start,對結果進行分片處理,索引位置
# num,對結果進行分片處理,索引後面的num個元素
# 如:
# ZADD myzset 0 aa 0 ba 0 ca 0 da 0 ea 0 fa 0 ga
# r.zrangebylex('myzset', "-", "[ca") 結果為:['aa', 'ba', 'ca']
# 更多:
# 從大到小排序
# zrevrangebylex(name, max, min, start=None, num=None)
zrem(name, values)
123# 刪除name對應的有序集合中值是values的成員
# 如:zrem('zz', ['s1', 's2'])
zremrangebyrank(name, min, max)
1# 根據排行範圍刪除
zremrangebyscore(name, min, max)
1# 根據分數範圍刪除
zremrangebylex(name, min, max)
1# 根據值返回刪除
zscore(name, value)
1# 獲取name對應有序集合中 value 對應的分數
zinterstore(dest, keys, aggregate=None)
12# 獲取兩個有序集合的交集,如果遇到相同值不同分數,則按照aggregate進行操作
# aggregate的值為: SUM MIN MAX
zunionstore(dest, keys, aggregate=None)
12# 獲取兩個有序集合的並集,如果遇到相同值不同分數,則按照aggregate進行操作
# aggregate的值為: SUM MIN MAX
zscan(name, cursor=0, match=None, count=None, score_cast_func=float)
zscan_iter(name, match=None, count=None,score_cast_func=float)
1# 同字串相似,相較於字串新增score_cast_func,用來對分數進行操作
其他常用操作
delete(*names)
1# 根據刪除redis中的任意資料型別
exists(name)
1# 檢測redis的name是否存在
keys(pattern='*')
1234567# 根據模型獲取redis的name
# 更多:
# KEYS * 匹配資料庫中所有 key 。
# KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
# KEYS h*llo 匹配 hllo 和 heeeeello 等。
# KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo
expire(name ,time)
1# 為某個redis的某個name設定超時時間
rename(src, dst)
1# 對redis的name重新命名為
move(name, db))
1# 將redis的某個值移動到指定的db下
randomkey()
1# 隨機獲取一個redis的name(不刪除)
type(name)
1# 獲取name對應值的型別
scan(cursor=0, match=None, count=None)
scan_iter(match=None, count=None)
1# 同字串操作,用於增量迭代獲取key
4、管道
redis-py預設在執行每次請求都會建立(連線池申請連線)和斷開(歸還連線池)一次連線操作,如果想要在一次請求中指定多個命令,則可以使用pipline實現一次請求指定多個命令,並且預設情況下一次pipline 是原子性操作。
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/env python # -*- coding:utf-8 -*- import redis pool = redis.ConnectionPool(host = '10.211.55.4' , port = 6379 ) r = redis.Redis(connection_pool = pool) # pipe = r.pipeline(transaction=False) pipe = r.pipeline(transaction = True )#True為開啟同時請求多個指令的功能 pipe. set ( 'name' , 'alex' ) pipe. set ( 'role' , 'sb' ) pipe.execute() |