#-*-coding:utf-8-*- import redis # 鏈接池鏈接使用,節省了每次鏈接用的時間 conn_pool = redis.ConnectionPool(host='localhost',port=6379) # 第一個客戶端訪問 re_pool = redis.Redis(connection_pool=conn_pool) # 第二個客戶端訪問 re_pool2 = redis.Redis(connection_pool=conn_pool) # key value存儲到redis數據庫 try: re_pool.set('chinese1', 'hello_world') re_pool2.set('chinese2', 'hello_python') except Exception as e: print(e) # 根據key獲取存的數據的內容 data_info = re_pool.get('chinese1') data_info2 = re_pool.get('chinese2') # 輸出從redis庫中取出來的數據的內容 print(data_info) print(data_info2) # 獲取兩個鏈接的信息 id1 = re_pool.client_list() id2 = re_pool2.client_list() # 輸出兩個鏈接的id,判斷是否一致 print('re_pool_id{}======re_pool2_id{}'.format(id1[0]['id'], id2[0]['id']))
redis的隊列效率高,並且簡單易用。python
從左往右插入隊列redis
查看插入的數據
import redis
import json數據庫
# redis鏈接 re_queue = redis.Redis(host='localhost', port=6379 ) # 順序插入五條數據到redis隊列,sort參數是用來驗證彈出的順序 num = 0 for i in range(0, 5): num = num + 1 # params info params_dict = {"channel":"facebook", "operate":"publish", "sort":num} # 從左往右入隊到redis re_queue.lpush("params_info", json.dumps(params_dict)) # 查看目標隊列數據 result = re_queue.lrange("params_info", 0, 10) print(result) # 結果輸出 # [b'{"channel": "facebook", "operate": "publish", "sort": 5}', b'{"channel": "facebook", "operate": "publish", "sort": 4}', b'{"channel": "facebook", "operate": "publish", "sort": 3}', b'{"channel": "facebook", "operate": "publish", "sort": 2}', b'{"channel": "facebook", "operate": "publish", "sort": 1}']
從左往右,第一個進的確定是在最右邊,要處理第一個,就要從右往左彈出json
rpush從右往左入隊,第一個在最左邊,lpop從左邊彈出緩存
返回列表的長度code