import redis
import time
from threading import Thread, Lock
# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)
IP_POOL_KEY = 'ip_pool'
lock = Lock()
def add_ip(ip):
# 添加IP到有序集合,使用当前时间戳作为score
with lock:
r.zadd(IP_POOL_KEY, {ip: time.time()})
def get_ip():
# 获取当前时间戳
current_time = time.time()
# 查找2分钟内的有效IP
with lock:
# 获取最早添加的IP
ips = r.zrangebyscore(IP_POOL_KEY, current_time - 120, current_time, start=0, num=1)
if ips:
ip = ips[0].decode('utf-8')
# 删除已获取的IP
r.zrem(IP_POOL_KEY, ip)
return ip
return None
def worker(worker_id):
while True:
ip = get_ip()
if ip:
print(f"Worker {worker_id} 获取到IP: {ip}")
# 模拟使用IP
# ...
else:
print(f"Worker {worker_id} 没有获取到IP")
break
# 示例用法
add_ip('192.168.1.1')
add_ip('192.168.1.2')
# 创建多个工作线程
threads = [Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
# 定期清理过期IP
def cleanup_expired_ips():
while True:
with lock:
# 删除2分钟前的IP
r.zremrangebyscore(IP_POOL_KEY, 0, time.time() - 120)
time.sleep(60) # 每分钟清理一次
# 启动清理线程
cleanup_thread = Thread(target=cleanup_expired_ips, daemon=True)
cleanup_thread.start()