秒杀
''' 秒杀程序 ''' import os import arrow import redis from multiprocessing import Pool from redlock.lock import RedLock HOTKEY = 'num' # 设置秒杀数量 r = redis.Redis(host='localhost', port=6379) # 秒杀函数 def miaosha(): name = os.getpid() # 获取pid 主要是知道哪个pid执行任务 v = r.get(HOTKEY) if int(v) > 0: print (name, '库存',int(v)) r.decr(HOTKEY) # 自减1 else: print(name,'商品库存为0') # 不加锁,每5秒中执行一次秒杀函数 def run_without_lock(name): while True: if arrow.now().second % 5 == 0: miaosha() # 秒杀函数 return # 使用redlock 模块 rlock = RedLock('miaosha',[{'host': 'localhost','port': 6379,'db': 8,}]) # 使用 锁 def run_with_redis_lock(name): while True: if arrow.now().second % 5 == 0: # 获取锁 if rlock.acquire(): # 秒杀函数 miaosha() # 释放锁 rlock.release() return if __name__ == '__main__': p = Pool(80) # 进程池 r.set(HOTKEY, 10) # 设置10件商品 for i in range(80): # p.apply_async(run_without_lock, args=(i,)) # 异步非阻塞 p.apply_async(run_with_redis_lock, args=(i,)) p.close() p.join() print('执行完毕')