短时间内点击 同一操作,进行缓存

介绍

在开发过程中,如果存在查询很费时间,还经常要点击同一个操作的时候,我们可以使用下面的方式;查询后我们先把数据存在redis中,设置一个过期时间,如果在过期时间内,他在此进行了本次操作,我们可以直接返回给他redis中缓存的数据,而不用在此进行查询了。

进行缓存

import json
import logging
import pickle
import threading
import time
from redis import Redis

class Cache(Redis):
    def __init__(self, host, port, db, password):
        self.host = host
        self.port = port
        self.password = password
        self.db = db
        super(Cache, self).__init__(host=self.host, port=self.port, db=self.db, password=password)
ROUTE_CACHE = {"host":"127.0.0.1","port":"62432","db":2,"password":"********"}

class QueueService(object):
    q = Cache(**ROUTE_CACHE)
    TASK_KEY = "search_task_key"

    def __init__(self, func):
        self.func = func
        self.task = threading.Thread(target=self.start)
        self.task.daemon = True
        self.task.start()

    @staticmethod
    def send_task(key, **kwargs):
        d = {"key": key}
        # 存入一个状态
        QueueService.q.set(key, pickle.dumps({"task_status": 0}))
        kwargs.update(d)
        # 修改 上面存储的数据 填入 res 数据百分比(线程任务)
        QueueService.q.lpush(QueueService.TASK_KEY, json.dumps(kwargs))

     def start(self):
          while True:
               try:
                  time.sleep(2)
                  param = QueueService.q.rpop(QueueService.TASK_KEY)
               except Exception:
                  param = None
               if param:
                param = json.loads(param)
                key = param.pop("key")
                res_to_store = {"res": "数据", "task_status": 1}

                QueueService.q.set(key, pickle.dumps(res_to_store), ex=300)

上方代码是 链接了redis数据库,在有请求过来的时候,我们会有一个线程一直在跑,看是否有我们要处理的数据。

判断是否进行了缓存

    def get_result(key):
        result = QueueService.q.get(key)
        if not result:
            return -1, []
        res = pickle.loads(result)
        return res.get("task_status"), res.get("res")

这里的代码是,每次请求的时候,我们要先判断一下,redis 中是否有缓存,如果已经有缓存,我们可以直接拿缓存,而不用在此进行查询了。

原文地址:https://www.cnblogs.com/shangwei/p/14482746.html