处理方法
- 锁机制:使用
threading.Lock
,在对Redis进行读或写操作前获取锁,操作完成后释放锁,确保同一时间只有一个线程能访问Redis。
- 连接池:使用
redis - py
库提供的连接池,每个线程从连接池获取连接,避免多个线程竞争连接资源导致问题。
代码示例
import threading
import redis
# 创建Redis连接池
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
redis_client = redis.Redis(connection_pool=pool)
lock = threading.Lock()
def increment_counter():
with lock:
current_value = redis_client.get('counter')
if current_value is None:
current_value = 0
else:
current_value = int(current_value)
new_value = current_value + 1
redis_client.set('counter', new_value)
print(f'Counter incremented to {new_value}')
# 创建多个线程
threads = []
for _ in range(5):
t = threading.Thread(target=increment_counter)
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()