博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebApi使用redis模拟抢购场景
阅读量:4031 次
发布时间:2019-05-24

本文共 5679 字,大约阅读时间需要 18 分钟。

Redis客户端连接使用git 上的csredis

本文示例代码在vs2015中调试,使用的是git上一个低版本代码,不支持net core,位置:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using CSRedis;namespace CommonWeb.Common{    public class RedisHelper    {        static RedisClient redisClient = null;        static object rc = new object();        static object redisUpdater = new object();        public RedisHelper(string host,int port)        {            if (null == redisClient)            {                lock (rc)                {                    if (null == redisClient)                    {                        redisClient = new RedisClient(host, port);                    }                }            }        }        public long placeOrder()        {            long result = 0;            try            {                long lngBanlance = 0;                long qty = 0;                lock (redisUpdater)                {                    long.TryParse(redisClient.Get("Iphone"), out lngBanlance);                }                if (lngBanlance <= 0) return result;                lock (redisUpdater)                {                                         qty = redisClient.Decr("Iphone");                }                if (qty >= 0) result = 1;            }            catch (Exception ex)            { }            return result;        }        public string setSaleItemQTY(string key,int qty)        {            try            {                redisClient.Set(key, qty);                return redisClient.Get(key);            }            catch(Exception ex)            {                return "";            }        }    }}

 

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using Newtonsoft.Json.Linq;using CommonWeb.Common;using Utility.HttpHelper;namespace RestfulService.Controllers{    public class BuyController : ApiController    {        [HttpPost]        public HttpResponseMessage PlaceOrder(JObject postData)        {            UtilHttpResult httpResult;            try            {                string consumer = postData["consumer"].ToString();                RedisHelper redisHelper = new RedisHelper("192.168.197.132", 6379);                long order = redisHelper.placeOrder();                if(order == 1)                {                    httpResult = UtilHttpResult.ok(string.Format("{0}下单成功!{1}", consumer, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")));                }                else                {                    httpResult = UtilHttpResult.ok(string.Format("{0},您好,你购买的商品已售完!{1}", consumer, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")));                }            }            catch(Exception ex)            {                httpResult = UtilHttpResult.fail("系经繁忙,请稍后!");            }            return httpResult.ToResponseMessage();        }    }}

 在WinForm客户端中模拟5000人抢购

RedisClient redis = null;        private void btnRedis_Click(object sender, EventArgs e)        {            bgWorker.DoWork += new DoWorkEventHandler(this.bgWorker_DoWork);            bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;            redis = new RedisClient("192.168.197.132", 6379);            redis.Set("Iphone", 10);            Console.WriteLine("现有{0}台,开始抢购", redis.Get("Iphone"));            bgWorker.RunWorkerAsync();            btnRedis.Enabled = false;            redis.Dispose();        }        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)        {            bool bSell = true;            long qty = 0;            Parallel.For(0, 5000, (i) =>            {                var param_dic = new Dictionary
() { { "consumer", "Consumer"+i.ToString()} }; var httpResult = ApiUtility.DoPostParameter(ApiManager.ApiUrl.PlaceOrder, param_dic, true); if (httpResult != null) { Console.WriteLine(httpResult["Data"]); } }); #region task //List
taskList = new List
(); //TaskFactory taskFactory = Task.Factory; //for(int i=0;i<5000;i++) //{ // taskList.Add(taskFactory.StartNew((count) => // { // try // { // var param_dic = new Dictionary
() // { // { "consumer", "Consumer"+count.ToString()} // }; // var httpResult = ApiUtility.DoPostParameter(ApiManager.ApiUrl.PlaceOrder, param_dic, true); // if (httpResult != null) // { // Console.WriteLine(httpResult["Data"]); // } // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // } // }, i)); //} //Task.WaitAll(taskList.ToArray()); #endregion Console.WriteLine("现有{0}台,抢购结束", redis.Get("Iphone")); Action act = delegate () { btnRedis.Enabled = true; }; this.Invoke(act); } private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { bgWorker.RunWorkerCompleted -= bgWorker_RunWorkerCompleted; bgWorker.DoWork -= new DoWorkEventHandler(this.bgWorker_DoWork); }

 代码中Task与Parallel均有验证,执行顺序不同比较明显,其它没过多关注。本文算是记录的学习笔记吧,供以后对比。

 

转载地址:http://ugqbi.baihongyu.com/

你可能感兴趣的文章
一个ahk小函数, 实现版本号的比较
查看>>
IP报文格式学习笔记
查看>>
autohotkey快捷键显示隐藏文件和文件扩展名
查看>>
Linux中的进程
查看>>
学习python(1)——环境与常识
查看>>
学习设计模式(3)——单例模式和类的成员函数中的静态变量的作用域
查看>>
自然计算时间复杂度杂谈
查看>>
当前主要目标和工作
查看>>
POJ 2363 Blocks(我的水题之路——立方体体积和表面积,暴力)
查看>>
POJ 2390 Bank Interest(我的水题之路——double和floa计算差别)
查看>>
POJ 2459 Feed Accounting(我的水题之路——英文题啊!!!)
查看>>
POJ 2470 Ambiguous permutation(我的水题之路——位置和值的队列)
查看>>
POJ 2498 StuPId(我的水题之路——from back to front- -!)
查看>>
POJ 2535 Very Simple Problem(我的水题之路——看错题)
查看>>
POJ 2538 WERTYU(我的水题之路——键盘错位)
查看>>
POJ 2551 Ones(我的水题之路——重点,末尾有几个1)
查看>>
POJ 2562 Primary Arithmetic(我的水题之路——模拟加法进位)
查看>>
POJ 2575 Jolly Jumpers(我的水题之路——数组绝对差值为1到n-1)
查看>>
POJ 2578 Keep on Truckin'(我的水题之路——谁先大于168)
查看>>
POJ 2579 Blurred Vision(我的水题之路——四方格平均值)
查看>>