from redis_db import pool
import redis
import random
from concurrent.futures import ThreadPoolExecutor
s = set()
while True:
if len(s) == 1000:
break
num = random.randint(10000, 100000)
s.add(num)
# print(s)
con = redis.Redis(
connection_pool=pool
)
try:
con.delete("kill_total", "kill_num", "kill_flag", "kill_user")
con.set("kill_total", 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
executor = ThreadPoolExecutor(50)
def buy():
connection = redis.Redis(
connection_pool=pool
)
pipline = connection.pipeline()
try:
if connection.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")
user_id = s.pop()
pipline.rpush("kill_user", user_id)
pipline.execute()
print(num)
except Exception as e:
# print(e)
pass
finally:
if "pipline" in dir():
pipline.reset()
del connection
for i in range(0, 1000):
executor.submit(buy)
print("秒杀已经结束")
2020-08-08 22:26:02
------------------------------->1
for i in range(0, 1000):
executor.submit(buy)
控制台:
C:\Python38\python.exe D:/1-pythonstudy/pycharmpro/redis_demo/buy_ex10.py
0
1
2
3
4
5
6
7
8
秒杀已经结束
9
10
11
12
13
14
15
16
17
18
19
20
21
Process finished with exit code 0
秒杀已经结束位置很奇怪
2020-08-08 22:27:31
----------------------->2
for i in range(0, 1000):
executor.submit(buy())
控制台:
C:\Python38\python.exe D:/1-pythonstudy/pycharmpro/redis_demo/buy_ex10.py
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
秒杀已经结束
Process finished with exit code 0
第一种抢不到50个是不是线程和主线程并列了的问题??
求老师解答^_^
2020-08-08 22:28:56
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星