openrstry 限流 是否有清零逻辑 连接池

 

openrstry  限流  是否有清零逻辑

 https://github.com/openresty/lua-resty-limit-traffic

 

 

# encoding=utf-8
# Shawn 2020/4/28 10:31
from asgiref.sync import async_to_sync


class ABCBucketToken:
    def __init__(self):
        pass

    def connect_bucket(self):
        pass

    def refresh_token(self):
        pass

    def check_token(self):
        pass

    def disconnect_bucket(self):
        pass

    def __del__(self):
        pass


class BizBucketToken(ABCBucketToken):
    factory_req_id = lambda k: 'BizBucketToken.' + k
    class_var_bucket_created = False

    def __init__(self, req_id='anonymoususer', limit=16, window_second=32):
        self.req_id = BizBucketToken.factory_req_id(req_id)
        self.limit = limit
        self.window_second = window_second
        # TODO
        self.connect_bucket()
    @classmethod
    def connect_bucket(cls):
        if cls.class_var_bucket_created:
            return
        # TODO cnf
        # TODO check alive
        def get_redis_conf():
            return 'redis://:pwd@rcs.com:6379/2'

        async def create_redis_pool(i: str):
            import aioredis
            pool = await aioredis.create_redis_pool(i)
            return pool

        redis_conf = get_redis_conf()
        redis_pool = async_to_sync(create_redis_pool)(redis_conf)
        cls.bucket = redis_pool
        cls.class_var_bucket_created=True
    def handle_token(self):
        to_throttle = False
        pttl = async_to_sync(self.bucket.pttl)(self.req_id)
        if pttl == -2:
            async_to_sync(self.bucket.set)(self.req_id, self.limit)
            async_to_sync(self.bucket.pexpire)(self.req_id, self.window_second * 1000)
        elif pttl == -1:
            async_to_sync(self.bucket.pexpire)(self.req_id, self.window_second * 1000)
        elif pttl == 0:
            # TODO
            pass
        elif pttl > 0:
            r = async_to_sync(self.bucket.get)(self.req_id)
            r = int(r)
            if r >= 1:
                async_to_sync(self.bucket.set)(self.req_id, r - 1)
            else:
                to_throttle = True
        return to_throttle

    def disconnect_bucket(self):
        pass

    def __del__(self):
        pass


if __name__ == 'main':
    pass

  

连接池

uid = get_uid(request)
BizBucketToken.connect_bucket()
r = BizBucketToken(req_id=uid, limit=160, window_second=32)
to_throttle = r.handle_token()




 

posted @ 2019-05-31 20:45  papering  阅读(432)  评论(0编辑  收藏  举报