redis 秒杀demo

redis_db

  • 连接数据库
import redis

try:
    pool = redis.ConnectionPool(
        host="localhost", port=6379, password="123456", db=0, max_connections=200
    )
except Exception as e:
    print(e)

thread

  • 多线程操作
from concurrent.futures import ThreadPoolExecutor

from redis_db import pool
import redis
import random


conn = redis.Redis(connection_pool=pool)

user_list = set()
while True:
    if len(user_list) == 300:
        break
    user_id = random.randint(10000, 99999)
    user_list.add(user_id)

try:
    # 几个关键参数 kill_number, kill_flag, kill_total, kill_flag
    conn.delete("kill_number", "kill_flag", "kill_total", "kill_user")
    conn.set("kill_number", 0)
    conn.set("kill_total", 10)
    conn.psetex("kill_flag", 20000, 1)

except Exception as e:
    print(e)
finally:
    del conn


# 模拟多线程抢票
executer = ThreadPoolExecutor(200)


def buy():
    r = redis.Redis(connection_pool=pool)
    # 事务的处理
    pipline = r.pipeline()
    try:
        if r.exists("kill_flag"):
            pipline.watch("kill_number", "kill_user")
            total = int(pipline.get("kill_total").decode("utf-8"))
            num = int(pipline.get("kill_number").decode("utf-8"))
            if num < total:
                pipline.multi()
                pipline.incr("kill_number")
                user_id = user_list.pop()
                pipline.rpush("kill_user", user_id)
                pipline.execute()
            else:
                r.delete("kill_flag")

    except Exception as e:
        print(e, "--")

    finally:
        # 回收
        pipline.reset()
        del r


if __name__ == "__main__":
    # 开始执行
    for i in range(0, 200):
        executer.submit(buy)

    print("DONE!")

原文链接: redis 秒杀demo 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-734.html )

发表评论

0则评论给“redis 秒杀demo”