关于scrapy 框架 管道 查询数据库后,直接批量导入redis做缓存的问题
具体步骤看详情代码:
class MohurdRedis(object):
# 打开数据库
def __init__(self):
self.db_conn = redis.StrictRedis(host='localhost', port=6379, db=12)
self.conn = pymysql.connect(user=MYSQL_CONFIG['user'], passwd=MYSQL_CONFIG['passwd'], db=MYSQL_CONFIG['db'],
host=MYSQL_CONFIG['host'],
charset="utf8",
use_unicode=True) # 连接mysql
self.cursor = self.conn.cursor() # 建立游标
def open_spider(self, spider):
self.insert_url_db()
# 插入数据库 url
def insert_url_db(self):
try:
p = self.db_conn.pipeline()
self.cursor.execute("""SELECT DETAIL_ID FROM sm_record_information""")
rows = self.cursor.fetchall()
for row in rows:
if row[0]:
print(row[0])
p.sadd("detail_id", row[0])
print("------2+", row[0])
data = p.execute()
print(data)
except Exception as e:
logging.warning('插入数据 操作失败>>>>', e)
# 关闭数据库
def close_spider(self):
self.db_conn.connection_pool.disconnect()
self.cursor.close()
self.conn.close()
上面的代码就是实现的全部逻辑, 具体的逻辑为: 先查询数据库后,传入redis的管道,通过管道的异步操作,实现批量大数据的导入,几百万的数据 差不多几十秒吧。