# -*- coding: utf-8 -*-
import redis
import threading
import time
class Test(object):
def __init__(self):
# 创建连接池
self.pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
self.r = redis.Redis(connection_pool=self.pool)
# 删除key
self.r.delete('name')
def put_redis(self):
# print('-------------1--------------')
# 存数据
for i in range(100):
# print('-------------4--------------')
self.r.rpush('name', i)
time.sleep(0.5)
def print_redis(self):
# print('-------------2--------------')
# 读数据
while True:
# print('-------------3--------------')
if self.r.llen('name') == 100:
print(self.r.llen('name'))
break
print(self.r.llen('name'))
time.sleep(0.2)
def run(self):
'''程序开始'''
# 创建线程
put_url = threading.Thread(target=self.put_redis)
print_url = threading.Thread(target=self.print_redis)
# 守护线程的方式
put_url.setDaemon(True)
print_url.setDaemon(True)
# 开启线程
put_url.start()
print_url.start()
# 等待
put_url.join()
print_url.join()
# 删除key
self.r.delete('name')
if __name__ == '__main__':
test = Test()
test.run()
打印结果: