client_spider_mongo.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # coding:utf-8
  2. import time
  3. from a2s.tools import json_serialize, json_deserialize
  4. from a2s.a2s_client import a2s_execute
  5. from docs.config import ReluMongodb
  6. from util.mogodb_helper import MongoDBInterface
  7. from pymongo import MongoClient
  8. from datetime import datetime, timedelta
  9. from elasticsearch import Elasticsearch
  10. #直接给es数据打分,并将结果存入mongo库,不在拉取数据打分
  11. ReluClient = MongoDBInterface(ReluMongodb)
  12. # 评估服务配置
  13. a2s_ip = "172.20.100.235:9090"
  14. # a2s_ip = "172.17.0.11:9090"
  15. topic = "quality_bid"
  16. #本地测试用的主题
  17. # topic = "test_quality_bid"
  18. timeout = 180
  19. # 获取当前时间
  20. now = datetime.now()
  21. # current_datetime = int(now.timestamp())
  22. # 计算昨天的时间
  23. yesterday = now - timedelta(days=1)
  24. # 获取昨天早上8点的时间
  25. yesterday_8_am = datetime(yesterday.year, yesterday.month, yesterday.day, 8, 0, 0)
  26. # 转换为时间戳(秒级)
  27. # current_datetime = int(yesterday_8_am.timestamp())
  28. #create_time,用于批次字段,值为数据的年月日:2025-02-12,1739289600,1739894400
  29. current_datetime=int(1743004800)
  30. # 时间段
  31. start_date = int(datetime(2025, 3, 27, 8, 0, 0).timestamp()) # 2025-01-20 00:00:00
  32. end_date = int(datetime(2025, 3, 27, 12, 0, 0).timestamp()) # 2025-01-20 23:59:59
  33. # ES 连接配置
  34. es_host = "http://127.0.0.1:19800"
  35. es_username = "jianyuGr"
  36. es_password = "we3g8glKfe#"
  37. # 初始化 Elasticsearch 客户端
  38. es_client = Elasticsearch(es_host,http_auth=(es_username, es_password),retry_on_timeout=True) # 使用基本认证
  39. # 开始评估
  40. def start_quality(data: dict, rules_id: int, a2s_ip, topic, timeout, retry=3):
  41. # 本次不使用SSL,所以channel是不安全的
  42. row = {"data": data, "rules_id": rules_id}
  43. bytes_data = json_serialize(row)
  44. for t in range(retry):
  45. print("topic",topic)
  46. try:
  47. resp_data = a2s_execute(a2s_ip, topic, timeout, bytes_data)
  48. if resp_data is None:
  49. continue
  50. result = json_deserialize(resp_data)
  51. return result
  52. except Exception as e:
  53. print(e)
  54. return {}
  55. # 获取规则ID
  56. def get_rule(company, version):
  57. rule_id = ReluClient.find_rule_by_company(ReluMongodb["col"], company, version)
  58. return rule_id
  59. def insert_batch_data_mongo(collection,params):
  60. """
  61. 执行批量插入数据到 MongoDB
  62. """
  63. # 将参数转换为字典列表
  64. documents=["mongoid","toptype","subtype","site","spidercode","channel","comeintime", "area","city","district","error_type","create_time"]
  65. doc={}
  66. for indx,param in enumerate(params):
  67. doc[documents[indx]] =param
  68. print(f"{doc}数据")
  69. # 插入数据
  70. try:
  71. collection.insert_one(doc) # `ordered=False` 忽略重复数据错误
  72. print(f"{doc}数据已成功插入到 MongoDB")
  73. except Exception as e:
  74. print("插入数据时发生错误:", e)
  75. def get_last_processed_id():
  76. """
  77. 获取上次处理的最大 ID (例如从数据库或文件中读取)
  78. """
  79. # 这里假设从文件读取中断 ID,你也可以从数据库或 Redis 等存储获取
  80. try:
  81. with open('docs/last_processed_id.txt', 'r') as f:
  82. last_id = f.read().strip()
  83. if last_id:
  84. return last_id
  85. else:
  86. return None
  87. except FileNotFoundError:
  88. return None
  89. def save_last_processed_id(last_id):
  90. """
  91. 保存当前处理的最大 ID,用于恢复
  92. """
  93. with open('docs/last_processed_id.txt', 'w') as f:
  94. f.write(str(last_id))
  95. def batch_load_data():
  96. """
  97. 批量数据质量检查
  98. """
  99. # 规则查询,根据必要条件 公司名称(用户ID)、版本号
  100. rules_id = get_rule("北京剑鱼信息技术有限公司", "v1.2")
  101. print(rules_id)
  102. #初始化mongo库
  103. conn = MongoClient('172.20.45.129', 27002, unicode_decode_error_handler="ignore").data_quality
  104. coll_user = conn["bid_analysis"]
  105. # 获取上次处理的 ID,如果没有,则从头开始
  106. last_processed_id = get_last_processed_id()
  107. print(f"上次处理的 ID: {last_processed_id}")
  108. # 获取ES数据
  109. es_query = {
  110. "query": {
  111. "bool": {
  112. "filter": [
  113. {
  114. "range": {
  115. "comeintime": {
  116. "gte": start_date,
  117. "lt": end_date
  118. }
  119. }
  120. }
  121. ]
  122. }
  123. },
  124. "sort": [
  125. {"_id": {"order": "asc"}} # 如果 comeintime 相同,再按 _id 排序
  126. ],
  127. "size": 100 # 每次返回的数据量
  128. }
  129. # 如果有上次处理的 ID,使用 `search_after` 进行分页
  130. if last_processed_id:
  131. es_query["search_after"] = [last_processed_id] # 确保传入的是字符串类型的 _id
  132. try:
  133. # 使用 scroll API 来分批获取数据
  134. response = es_client.search(index="bidding", body=es_query, size=100)
  135. hits = response['hits']['hits']
  136. total_hits = response['hits']['total']['value'] # 获取数据总量
  137. print(f"数据总量: {total_hits}")
  138. while hits:
  139. print(f"---- 批次开始 ----")
  140. max_id = None
  141. for hit in hits:
  142. item = hit["_source"]
  143. print("------一条数据开始--------")
  144. max_id = hit["_id"]
  145. print(f"正在处理数据: {max_id}")
  146. item["_id"] = str(hit["_id"])
  147. # 质量检查逻辑
  148. result = start_quality(item, rules_id, a2s_ip, topic, timeout)
  149. print(result)
  150. code = result.get("code")
  151. if code != 200:
  152. # 数据出错,跳过
  153. continue
  154. data = result.get("data", {})
  155. # 数据插入到 mongo
  156. toptype = item.get("toptype", "")
  157. subtype = item.get("subtype", "")
  158. site = item.get("site", "")
  159. spidercode = item.get("spidercode", "")
  160. channel = item.get("channel", "")
  161. comeintime = item.get("comeintime", "")
  162. area = item.get("area", "")
  163. city = item.get("city", "")
  164. district = item.get("district", "")
  165. error_type=data
  166. create_time = current_datetime
  167. params = (item["_id"], toptype, subtype, site, spidercode,channel, comeintime, area, city, district, error_type,create_time)
  168. insert_batch_data_mongo(coll_user, params)
  169. print("------一条数据结束------")
  170. # 保存当前批次处理的最大 ID
  171. if max_id:
  172. save_last_processed_id(max_id)
  173. print(f"保存当前处理的最大 ID: {max_id}")
  174. # 批次结束的打印信息
  175. print("---- 当前批次数据处理完成 ----")
  176. # 获取下一批数据
  177. search_after = hits[-1]["_id"] # 获取当前批次最后一条数据的 _id 作为下一批的起始点
  178. es_query["search_after"] = [search_after] # 保持 _id 类型一致
  179. response = es_client.search(index="bidding", body=es_query, size="100")
  180. hits = response['hits']['hits']
  181. # 如果没有更多数据,跳出循环
  182. if not hits:
  183. print("没有更多数据,结束批次处理")
  184. break
  185. print("数据处理完成")
  186. except Exception as e:
  187. print(f"错误: {e}")
  188. time.sleep(10)
  189. finally:
  190. if conn.is_connected():
  191. conn.close() # 确保连接关闭
  192. print("MySQL 连接已关闭")
  193. if __name__ == '__main__':
  194. batch_load_data()