还是新建一个 redis_db.py

import redis

try:
    pool = redis.ConnectionPool(
        host="localhost",
        port=6379,
        password='',
        db=0,
        max_connections=100
    )
except Exception as e:
    print('redis链接错误:{0}'.format(e))

然后开始代码:

"""python使用reids模拟1000人的在线抢购"""
import executor as executor

from redis_db import pool
import redis
from concurrent.futures import ThreadPoolExecutor
import random

s = set()
while True:
    if len(s) == 1000:
        break
    num = random.randint(10000, 100000)
    s.add(num)

con = redis.Redis(
    connection_pool=pool
)

try:
    con.delete("kill_total", "kill_num", "kill_flag", "kill_user")
    # 从新设置秒杀商品信息
    con.set("kill_total", 50) #抢购商品50件
    con.set("kill_num", 0)
    con.set("kill_flag", 1)
    # 设置过期时间
    con.expire("kill_flag", 600)
except Exception as e:
    # 异常提示
    print(e)
finally:
    # 关闭链接
    del con

# 线程池,200
excutor = ThreadPoolExecutor(200)


def buy():
    """模拟购买东西"""
    conn = redis.Redis(
        connection_pool=pool
    )
    pipline = conn.pipeline()
    try:
        # 判断秒杀是否开启
        if conn.exists("kill_flag") == 1:
            # 观察数据
            pipline.watch("kill_num", "kill_user")
            total = int(pipline.get("kill_total").decode("utf-8"))
            num = int(pipline.get("kill_num").decode("utf-8"))
            if num < total:
                # 打开事务
                pipline.multi()
                # 抢购商品
                pipline.incr("kill_num")  # 每次加1
                # 获取抢购成功的用户ID,上面的S列表里面去一个ID出来
                user_id = s.pop()
                # 把提取出来的ID存入reids
                pipline.rpush("kill_user", user_id)
                # 提交事务
                pipline.execute()
    except Exception as ee:
        print(ee)
    finally:
        # 关闭事务,回收资源
        if "pipline" in dir():
            pipline.reset()
        del conn


for i in range(0, 1000):
    """
    线程池循环,模拟一千人抢购,提交1000个进程
    """
    excutor.submit(buy())

print("秒杀结束...")

最终的效果可以查看redis里面的数据写入情况,一目了然。

最后修改:2021 年 07 月 13 日 10 : 35 AM
如果觉得我的文章对你有用,请随意赞赏