Przeglądaj źródła

上线 redis 中间件 , pipeline中添加 redis mq 过滤

罗俊辉 1 rok temu
rodzic
commit
146158d72d

+ 38 - 3
application/common/redis/pyredis.py

@@ -2,6 +2,7 @@
 Redis client Python
 @author luojunhui
 """
+import time
 
 import redis
 
@@ -9,14 +10,28 @@ import redis
 class RedisClient(object):
     """
     Redis client by python
+    Todo 如果 Redis 服务挂了,怎么做能够不影响业务
+    思路, 每次使用 redis 接口前先判断是否连接成功,如果连接失败则跳过 redis ,不影响全局
     """
 
     def __init__(self):
+        self.pool = None
         self.host = 'r-bp1mb0v08fqi4hjffu.redis.rds.aliyuncs.com'
         self.port = 6379
         self.db = 2
         self.password = 'Wqsd@2019'
-        self.pool = redis.Redis(host=self.host, port=self.port, db=self.db, password=self.password)
+
+    def connect(self):
+        """
+        connect to redis server
+        :return: bool
+        """
+        try:
+            self.pool = redis.Redis(host=self.host, port=self.port, db=self.db, password=self.password)
+            return True
+        except Exception as e:
+            print("connect to redis fail, the reason is {}".format(e))
+            return False
 
     def select(self, key):
         """
@@ -25,9 +40,29 @@ class RedisClient(object):
         """
         return self.pool.get(key)
 
-    def insert(self, key, value):
+    def insert(self, key, value, expire_time):
         """
         insert info from redis
         :return:
         """
-        self.pool.set(key, value)
+        self.pool.set(key, value, expire_time)
+
+    def delete(self, key):
+        """
+        delete key
+        :param key:
+        :return:
+        """
+        self.pool.delete(key)
+
+
+if __name__ == '__main__':
+    R = RedisClient()
+    if R.connect():
+        print(R.select(1))
+        R.insert(1, 2, 3)
+        print(R.select(1))
+        time.sleep(2)
+        print(R.select(1))
+        time.sleep(2)
+        print(R.select(1))

+ 27 - 10
application/pipeline/pipeline.py

@@ -1,3 +1,4 @@
+import hashlib
 import re
 import sys
 import os
@@ -6,6 +7,7 @@ import time
 sys.path.append(os.getcwd())
 
 from application.common import MysqlHelper, AliyunLogger
+from application.common.redis.pyredis import RedisClient
 
 
 class PiaoQuanPipeline(object):
@@ -23,6 +25,7 @@ class PiaoQuanPipeline(object):
         self.mysql = MysqlHelper(env=env, mode=mode, platform=platform)
         self.aliyun_log = AliyunLogger(platform=platform, mode=mode, env=env)
         self.account = account
+        self.red = RedisClient()
 
     def publish_time_flag(self):
         """
@@ -159,11 +162,35 @@ class PiaoQuanPipeline(object):
             return False
         return True
 
+    def mq_exists(self):
+        """
+        检测 mq 是否已经发送过了
+        :return:
+        """
+        if self.red.connect():
+            index_txt = "{}-{}".format(self.platform, self.item['video_id'])
+            index_md5 = hashlib.md5(index_txt.encode())
+            if self.red.select(index_md5):
+                self.aliyun_log.logging(
+                    code="2007",
+                    trace_id=self.trace_id,
+                    message="该视频 mq 已经发送"
+                )
+                return False
+            else:
+                self.red.insert(index_md5, int(time.time()), 43200)
+                return True
+        else:
+            return True
+
     def process_item(self):
         """
         全规则判断,符合规则的数据则return True
         :return:
         """
+        # 判断该 mq 是否已经发了
+        if not self.mq_exists():
+            return False
         if not self.publish_time_flag():
             # 记录相关日志
             return False
@@ -178,13 +205,3 @@ class PiaoQuanPipeline(object):
             return False
         return True
 
-
-# if __name__ == '__main__':
-#     sql_2 = f"""select create_time from crawler_video where video_id='18940470';"""
-#     Mysql = MysqlHelper(platform="xishiduoduo", mode="recommend")
-#     video_time = Mysql.select(sql=sql_2)
-#     print(video_time)
-#     print(video_time[0])
-#     print(video_time[0][0])
-#     print(type(video_time[0][0]))
-#     print(video_time[0][0].timestamp())

+ 9 - 8
application/pipeline/pipeline_dev.py

@@ -18,11 +18,11 @@ class PiaoQuanPipelineTest:
         update_time_stamp = self.item["update_time_stamp"]
         if self.platform == "gongzhonghao":
             if (
-                int(time.time()) - publish_time_stamp
-                > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
+                    int(time.time()) - publish_time_stamp
+                    > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
             ) and (
-                int(time.time()) - update_time_stamp
-                > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
+                    int(time.time()) - update_time_stamp
+                    > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
             ):
                 message = "发布时间超过{}天".format(
                     int(self.rule_dict.get("period", {}).get("max", 1000))
@@ -31,8 +31,8 @@ class PiaoQuanPipelineTest:
                 return False
         else:
             if (
-                int(time.time()) - publish_time_stamp
-                > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
+                    int(time.time()) - publish_time_stamp
+                    > 3600 * 24 * int(self.rule_dict.get("period", {}).get("max", 1000))
             ):
                 message = "发布时间超过{}天".format(
                     int(self.rule_dict.get("period", {}).get("max", 1000))
@@ -63,7 +63,7 @@ class PiaoQuanPipelineTest:
                     if int(self.rule_dict[key]["max"]) > 0
                     else 999999999999999
                 )
-                if key == "peroid": # peroid是抓取周期天数
+                if key == "peroid":  # peroid是抓取周期天数
                     continue
                 else:
                     flag = int(self.rule_dict[key]["min"]) <= int(self.item[key]) <= max_value
@@ -108,4 +108,5 @@ class PiaoQuanPipelineTest:
         if not self.download_rule_flag():
             # 记录相关日志
             return False
-        return True
+        return True
+