第二章,了解Mongodb保存數據
Mongodb對於每次插入的數據沒有要求,字段可以隨便變動,字段類型可以隨意變動。
Mongodb可以並發插入上萬條文檔,這是傳統關系型數據庫不能望其項背的。
1.從隊列Queue到Redis
在某些場景下,使用隊列可以提高程序的運行性能,但是如何選擇合適的隊列也需要仔細考慮。
2.了解“生產者、消費者”模式
廚師是生產者,負責生產,顧客是消費者,負責消費。廚師和顧客各做各的事,傳菜窗口就是隊列,它把生產者與消費者聯系在一起。
3實例、使用python實現隊列。
使用python自帶queue對象實現隊列:
1,使用python實現一個簡單生產者,消費者模型
2,使用python的queue對象做消息隊列。
在python使用多線程實現生產者與消費者的程序中,可以使用再帶的queue對象作為消費者和生產者的溝通的隊列。
在代碼中,生產者負責產生兩個數字,消費者負責把兩個數字相加。
producer生產者 import random import time import redis import json from threading import Thread class Producer(Thread): def __init__(self): super().__init__() # 調用Thread的初始化對象 self.queue = redis.Redis() def run(self): while True: a = random.randint(0, 10) b = random.randint(0, 10) print(f"生產者生產了兩個數字:{a},{b}") self.queue.rpush('producer',json.dumps((a,b))) time.sleep(2) producer = Producer() producer.start() while True: time.sleep(1)
1 consumer消費者 2 import random 3 import time 4 import redis 5 import json 6 7 from threading import Thread 8 9 10 class Consumer(Thread): 11 def __init__(self): 12 super().__init__() # 調用Thread的初始化對象 13 self.queue = redis.Redis() 14 15 def run(self): 16 while True: 17 name_tuple = self.queue.blpop('producer') 18 a,b =json.loads(name_tuple[1].decode()) 19 print(f"消費者消費了一組數,{a}+{b}={a+b}") 20 time.sleep(random.randint(0, 10)) 21 22 23 consumer = Consumer() 24 consumer.start() 25 while True: 26 time.sleep(1)