MS-API。AJAS
Posted gc1229
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MS-API。AJAS相关的知识,希望对你有一定的参考价值。
//1.获取秒杀商品详情接口
[Route("api/GetProduct")]
[HttpGet]
public ProductInfo GetProduct(int productId = 1)
{
ProductInfo info = new ProductInfo();
info.PId = 1;
info.SPName = "Iphone Xs Max 黑色";
info.SPimage = @"/image/1.png";
info.MarkPrice = 6999.99m;
info.KillPrice = 1999.9m;
info.KillStartTime = DateTime.Now.AddMinutes(-30);
info.KillEndTime = DateTime.Now.AddHours(1);
info.KillStokCount = 100;
info.KillStokCount = productId * 100;
//把秒杀的库存写进Redis里面
SetRedisValue("KillStokCount-" + productId, "100");
return info;
}
//2.秒杀下单
private void SetRedisValue(string key,string value)
{
RedisClient redisClient = new RedisClient("127.0.0.1");
redisClient.Set<string>(key, value);
}
/// <summary>
/// 获取Redis中的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private string GetRedisValue(string key)
{
RedisClient redisClient = new RedisClient("127.0.0.1");
return redisClient.Get<string>(key);
}
/// <summary>
/// 秒杀下单的接口
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("api/GetKill")]
public int KillOrder(OrderInfo order)
{
//res返回值表示
//1表示下单成功
//2表示库存不足
//3表示 三分钟之内只能点击一次
int res = 0;
#region 判断用户是不是在三分钟之内点击了一次,记录每次点击的时间
//同一个用户 在三分钟之内只能点击一次
//userId-1 2020-06-24 09:40:41
//userId-2 2020-06-24 09:41:20
var userKill = GetRedisValue("UserId-" + order.UserId);
if (!string.IsNullOrEmpty(userKill))
{
DateTime dateTime = Convert.ToDateTime(userKill);
var tmpvalue = DateTime.Now - dateTime;
if (tmpvalue.TotalMinutes < 3)
{
//用户三分钟之内只能点击一次
res = 3;
return res;
}
SetRedisValue("userId" + order.UserId, DateTime.Now.ToString());
}
else
{
//此处表示用户是第一次点击
SetRedisValue("userId" + order.UserId, DateTime.Now.ToString());
}
#endregion
#region 2.判断商品的库存够不够
ProductInfo info = new ProductInfo();
var maney = Convert.ToInt32(GetRedisValue("KillStokCount-" + info.PId));
if (maney > 0)
{
maney = maney - 1;
SetRedisValue("KillStokCount-" + info.PId, maney.ToString());
}
else
{
res = 2;
return res;
}
#endregion
return res;
}
}
------------------------------------------------------
以上是关于MS-API。AJAS的主要内容,如果未能解决你的问题,请参考以下文章