使用Redis List简单实现抢红包
在这里不讨论抢红包的算法,只用redis简单尝试解决抢红包。借助redis单线程和List的POP方法。
1 static void Main(string[] args) 2 { 3 IRedisHelper redisClient = RedisFactory.CreateRedisRepository(); 4 5 //初始化假数据 6 //红包的算法这里不关注 只用redis简单解决并发问题 7 double money = 20000; //200元 2W分 //微信群200人 //20人抢 //发10包 8 double singlePacket = 20000 / 10; 9 var key = "redisPacketKeyTest2"; 10 for (int i = 0; i < 10; i++) 11 { 12 redisClient.ListLeftPush(key, singlePacket); 13 } 14 15 //开抢 16 for (int i = 0; i < 20; i++) 17 { 18 new Thread((obj) => 19 { 20 Console.WriteLine("有人开抢"); 21 var count = (int) obj; 22 var result = redisClient.ListLeftPop<double>(key); 23 if (result > 0) 24 { 25 26 Console.WriteLine("第" + (count + 1) + "人抢到了" + result); 27 } 28 else 29 { 30 Console.WriteLine("第" + (count + 1) + "人没抢到"); 31 } 32 }).Start(i); 33 34 35 } 36 Console.Read(); 37 }