redis連接池的標準用法:
阿新 • • 發佈:2018-01-18
pty sad raise member div 操作 one 刪除 初始化
from .conf import HOST, PORT, POOL_NAME import redis redis_pool = redis.ConnectionPool(host=HOST, port=PORT, max_connections=20) class RedisOperator(object): """Redis 操作類""" def __init__(self): """初始化 Redis 連接""" # self._conn = redis.Po(HOST, PORT) self._conn = redis.Redis(connection_pool=redis_pool) def gets(self, total=1): """從池中返回給定數量的代理(取出但不刪除),當 total > pool.size 時,將返回 pool.size 個代理。 :param total: 返回的數量 :return: proxies, size=total """ tmp = self._conn.srandmember(POOL_NAME, total) return [s.decode(‘utf-8‘) for s in tmp] def puts(self, proxies): """將一定量的代理壓入 pool 中 :param proxies: :return: """ self._conn.sadd(POOL_NAME, *proxies) def pop(self): """彈出一個代理(取出並刪除) :return: proxy """ # if self.size == 0: # raise PoolEmptyError return self._conn.spop(POOL_NAME).decode(‘utf-8‘) @property def size(self): """返回 pool 的 size :return: pool.size """ return self._conn.scard(POOL_NAME) def _flush(self): """清空 Redis 中的全部內容 :return: None """ self._conn.flushall()
redis連接池的標準用法: