缓存:常用的缓存有CDN、反向代理、本地缓存(NoSql),分布式缓存。
其中CDN除了可以自建各地服务器,也可以购买云服务,反向代理Nginx只是设置,优化也比较简单,所以先从Redis开始学习:
1、Redis常见的有5种数据类型string/List/Set/Zset(Sorted Set)/Hash
2、应用场景:缓存分为会话缓存、全页缓存等,计数器,排行榜,消息队列系统
本次先从秒杀超卖问题谈起:
先看一个超卖问题:这里模拟一个产品的StockNumber库存数量为20,所启动在线程模拟获取库存。
这个TestSeckill,用于调用模拟秒杀:
运行一下,出现多个用户购买同一个产品的超卖现象:
-----------------以上为了展示问题!
因为是面向多用户,而且会有集群问题,并非一个进程内,在这种情况下,如果使用“锁”的方式就必须要使用分布式锁!
这里展示Redis方案:
======================================
using CSRedis; //C#推荐使用这个nuget包
using SeckillProject.extension;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace XXXProject
{
class Program
{
//Redis连接字符串
private static readonly string redisConnectionString = "127.0.0.1:6379,connectionTimeout=5000,allowAdmin=false,defaultDatabase=4";
static void Main(string[] args)
{
//可以应用到业务上的 Lua配合Redis实现分布式锁
TestSeckillSuper();
}
private static void TestSeckillSuper()
{
var threadNumber = 300; //秒杀并发数
var stockNumber = 10; //商品库存数
var key = "order_queue"; //将成功的用户及订单加入队列
var lockKey = "order_lock";
var csRedis = new CSRedisClient(redisConnectionString); //获取一个实例
csRedis.Del(key); //先清空队列
var isEnd = false; //
List<Task> taskList = new List<Task>();
for (int i = 0; i < threadNumber; i++)
{
var number = i;
taskList.Add(Task.Run(()=> {
Thread.Sleep(50);
if (isEnd) //先假设遇到结束,这样就不怕遇到海量并发
{
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}-用户{number}秒杀失败,已经抢完了");
}
// 定义一个所有线程唯一标识
var selfThread = $"{Thread.CurrentThread.ManagedThreadId}_用户{number}";
// 获取分布式锁
var redisLock = csRedis.RedisLock(lockKey, selfThread, 2);
if (redisLock)
{
var len = csRedis.LLen(key);
if (len>=stockNumber)
{
isEnd = true;
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}-用户{number}秒杀失败,已经抢完了");
} else
{
var value = $"{Thread.CurrentThread.ManagedThreadId}_用户{number}";
// 放入队列,处理订单入队列
csRedis.LPush(key, value);
// 解锁,防止误解锁
csRedis.RedisUnlock(lockKey, value);
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}-用户{number}秒杀成功!!!!");
}
}
}));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine("秒杀结束");
}
}
=============扩展方法==============
using CSRedis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XXXProject.extension
{
/// <summary>
/// CSRedisClient扩展类
/// </summary>
public static class RedisLockExtension
{
/// <summary>
/// Redis加锁方法
/// </summary>
/// <param name="client">连接Reids的客户端对象</param>
/// <param name="key">设置key</param>
/// <param name="value">设置的value</param>
/// <param name="expireTime">key的过期时间</param>
/// <returns></returns>
public static bool RedisLock(this CSRedisClient client, string key, object value, int expireTime)
{
// 使用超时机制,可以,但是业务执行时间如何把握呢?这里传入参数为
// lua脚本:加锁+过期时间是分开得2个步骤,一个脚本就是一个事务(不管里面有多少步骤都是保证原子性)
var luaScript = @"local isNx = redis.call('SETNX', KEYS[1],ARGV[1]) //建议全大写,object value对应这个ARGV[1]
if isNx == 1 then
redis.call('EXPIRE',KEYS[1],ARGV[2]) //KEYS[1]对应string key,ARGV[2]对应 int expireTime
return 1
end
return 0";
return client.Eval(luaScript, key, value, expireTime)?.ToString()=="1";
}
// 解锁方法
public static bool RedisUnlock(this CSRedisClient client, string key, string selfThread)
{
var luaScript = @"local getLock = redis.call('GET', KEYS[1])
if getLock == ARGV[1] then
redis.call('DEL',KEYS[1])
return 1
end
return 0";
return client.Eval(luaScript, key, selfThread)?.ToString()=="1";
}
}
}
=============