环境:之前一直是使用serverStack.Redis的客服端,
今天来使用一下StackExchange.Redis(个人感觉更加的人性化一些,也是免费的,性能也不会差太多),
版本为StackExchange.Redis V2.1.58 ,Core3.1

简单的说明(专业的术语参考资料网络和官网):官网地址:https://www.redis.net.cn/

Redis是一个开源的 ,由C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

Redis 是一个高性能的key-value数据库。Redis的出现,很大程度补偿了memcached这类key/value存储的不足,

提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便。

优点:

1 Redis读写性能优异,从内存当中进行IO读写速度快,支持超过100K+每秒的读写频率。

2 Redis支持Strings,

Lists, Hashes, Sets,Ordered Sets等数据类型操作。

3 Redis支持数据持久化,支持AOF和RDB两种持久化方式

4 Redis支持主从复制,主机会自动将数据同步到从机,可以进行读写分离。

5 Redis的所有操作都是原子性的,同时Redis还支持对几个操作全并后的原子性执行。

6 Redis是单线程多CPU,不需要考虑加锁释放锁,也就没有死锁的问题,效率高。

1:redis队列值入队出队,截图效果:

优化之前将近50秒了,这实在太慢了

优化后的效果:为5.55s的样子

2:redis发布与订阅截图效果:(一个发布者,四个订阅者)

3:redis秒杀,截图如下:单个进程秒杀ok

开多个进程时,会有超卖的现象:

4:redis值分布式锁,截图:

但是这样会比较耗资源

分布式锁ok库存为零就不在请求直接抛异常即可

上面通过测试的截图,简单的介绍了,Redis的队列(入队和出队),Redis发布与订阅,Redis分布式锁的使用,现在直接上代码 :

出队入队的WebApi Core3.1

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebApp.Controllers
{
using Microsoft.AspNetCore.Mvc;
using RedisPublishAndSubHelper;
[Route("api/[Controller]")]
[ApiController]
public class RedisTestController
{
[HttpGet("EnqueueMsg")]
public async Task<ApiResultObject> EnqueueMsgAsync(string rediskey, string redisValue)
{
ApiResultObject obj = new ApiResultObject();
try
{
long enqueueLong = default;
for (int i = ; i < ; i++)
{
enqueueLong = await MyRedisSubPublishHelper.EnqueueListLeftPushAsync(rediskey, redisValue + i);
}
obj.Code = ResultCode.Success;
obj.Data = "入队的数据长度:" + enqueueLong;
obj.Msg = "入队成功!";
}
catch (Exception ex)
{ obj.Msg = $"入队异常,原因:{ex.Message}";
}
return obj;
}
[HttpGet("DequeueMsg")]
public async Task<ApiResultObject> DequeueMsgAsync(string rediskey)
{
ApiResultObject obj = new ApiResultObject();
try
{
string dequeueMsg = await MyRedisSubPublishHelper.DequeueListPopRightAsync(rediskey);
obj.Code = ResultCode.Success;
obj.Data = $"出队的数据是:{dequeueMsg}";
obj.Msg = "入队成功!";
}
catch (Exception ex)
{
obj.Msg = $"入队异常,原因:{ex.Message}";
}
return obj;
}
}
}

出队入队的后端code WebApi:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebApp.Controllers
{
using Microsoft.AspNetCore.Mvc;
using RedisPublishAndSubHelper;
[Route("api/[Controller]")]
[ApiController]
public class RedisTestController
{
[HttpGet("EnqueueMsg")]
public async Task<ApiResultObject> EnqueueMsgAsync(string rediskey, string redisValue)
{
ApiResultObject obj = new ApiResultObject();
try
{
long enqueueLong = default;
for (int i = ; i < ; i++)
{
enqueueLong = await MyRedisSubPublishHelper.EnqueueListLeftPushAsync(rediskey, redisValue + i);
}
obj.Code = ResultCode.Success;
obj.Data = "入队的数据长度:" + enqueueLong;
obj.Msg = "入队成功!";
}
catch (Exception ex)
{ obj.Msg = $"入队异常,原因:{ex.Message}";
}
return obj;
}
[HttpGet("DequeueMsg")]
public async Task<ApiResultObject> DequeueMsgAsync(string rediskey)
{
ApiResultObject obj = new ApiResultObject();
try
{
string dequeueMsg = await MyRedisSubPublishHelper.DequeueListPopRightAsync(rediskey);
obj.Code = ResultCode.Success;
obj.Data = $"出队的数据是:{dequeueMsg}";
obj.Msg = "入队成功!";
}
catch (Exception ex)
{
obj.Msg = $"入队异常,原因:{ex.Message}";
}
return obj;
}
}
}

入队以及秒杀分布式锁的客服端的Code:

 using System;
using System.Threading;
using System.Threading.Tasks; namespace RedisPublishService
{
using RedisPublishAndSubHelper;
class Program
{
static void Main(string[] args)
{
#region 入队的code
{
int Index = ;
while (Index > )
{
//string msg = Console.ReadLine();
new MyRedisSubPublishHelper().PublishMessage("nihaofengge", $"你好风哥:Guid值是:{DateTime.Now}{Guid.NewGuid().ToString()}");
Console.WriteLine("发布成功!");
Index -= ;
}
Console.ReadKey();
}
#endregion #region 秒杀的code
{
try
{
Console.WriteLine("秒杀开始。。。。。");
for (int i = ; i < ; i++)
{
Task.Run(() =>
{
MyRedisSubPublishHelper.LockByRedis("mstest");
string productCount = MyRedisHelper.StringGet("productcount");
int pcount = int.Parse(productCount);
if (pcount > )
{
long dlong = MyRedisHelper.StringDec("productcount");
Console.WriteLine($"秒杀成功,商品库存:{dlong}");
pcount -= ;
System.Threading.Thread.Sleep();
}
else
{
Console.WriteLine($"秒杀失败,商品库存为零了!");
throw new Exception("产品秒杀数量为零!");//加载这里会比较保险
}
MyRedisSubPublishHelper.UnLockByRedis("mstest");
}).Wait();
}
}
catch (Exception ex)
{
Console.WriteLine($"产品已经秒杀完毕,原因:{ex.Message}");
}
Console.ReadKey();
}
#endregion
}
}
}

完整的code RedisHelper帮助类(测试并使用了部分方法的封装),

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace RedisPublishAndSubHelper
{
using StackExchange.Redis;
using StackExchange;
using System.Threading; public class MyRedisHelper
{
private static readonly string connectionRedisStr = string.Empty;// "47.107.87.32:6379,connectTimeout=1000,connectRetry=3,syncTimeout=10000";
static MyRedisHelper()
{
//在这里来初始化一些配置信息
connectionRedisStr = "12.23.45.12:6379,connectTimeout=1000,connectRetry=3,syncTimeout=10000";
} #region Redis string简单的常见同步方法操作
public static bool StringSet(string key, string stringValue, double senconds = )
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase db = conn.GetDatabase();
return db.StringSet(key, stringValue, TimeSpan.FromSeconds(senconds));
}
}
public static string StringGet(string key)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase db = conn.GetDatabase();
return db.StringGet(key);
}
} public static long StringInc(string key)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase db = conn.GetDatabase();
return db.StringIncrement(key);
}
} public static long StringDec(string key)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase db = conn.GetDatabase();
return db.StringDecrement(key);
}
}
public static bool KeyExists(string key)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase db = conn.GetDatabase();
return db.KeyExists(key);
}
}
#endregion #region List Hash, Set,Zset 大同小异的使用,比较简单,后续有时间再补上 #endregion #region 入队出队 #region 入队
/// <summary>
/// 入队right
/// </summary>
/// <param name="queueName"></param>
/// <param name="redisValue"></param>
/// <returns></returns>
public static long EnqueueListRightPush(RedisKey queueName, RedisValue redisValue)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
return conn.GetDatabase().ListRightPush(queueName, redisValue);
}
}
/// <summary>
/// 入队left
/// </summary>
/// <param name="queueName"></param>
/// <param name="redisvalue"></param>
/// <returns></returns>
public static long EnqueueListLeftPush(RedisKey queueName, RedisValue redisvalue)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
return conn.GetDatabase().ListLeftPush(queueName, redisvalue);
}
}
/// <summary>
/// 入队left异步
/// </summary>
/// <param name="queueName"></param>
/// <param name="redisvalue"></param>
/// <returns></returns>
public static async Task<long> EnqueueListLeftPushAsync(RedisKey queueName, RedisValue redisvalue)
{
using (var conn = await ConnectionMultiplexer.ConnectAsync(connectionRedisStr))
{
return await conn.GetDatabase().ListLeftPushAsync(queueName, redisvalue);
}
}
/// <summary>
/// 获取队列的长度
/// </summary>
/// <param name="queueName"></param>
/// <returns></returns>
public static long EnqueueListLength(RedisKey queueName)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
return conn.GetDatabase().ListLength(queueName);
}
} #endregion #region 出队
public static string DequeueListPopLeft(RedisKey queueName)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase database = conn.GetDatabase();
int count = database.ListRange(queueName).Length;
if (count <= )
{
throw new Exception($"队列{queueName}数据为零");
}
string redisValue = database.ListLeftPop(queueName);
if (!string.IsNullOrEmpty(redisValue))
return redisValue;
else
return string.Empty;
}
}
public static string DequeueListPopRight(RedisKey queueName)
{
using (var conn = ConnectionMultiplexer.Connect(connectionRedisStr))
{
IDatabase database = conn.GetDatabase();
int count = database.ListRange(queueName).Length;
if (count <= )
{
throw new Exception($"队列{queueName}数据为零");
}
string redisValue = conn.GetDatabase().ListRightPop(queueName);
if (!string.IsNullOrEmpty(redisValue))
return redisValue;
else
return string.Empty;
}
}
public static async Task<string> DequeueListPopRightAsync(RedisKey queueName)
{
using (var conn = await ConnectionMultiplexer.ConnectAsync(connectionRedisStr))
{
IDatabase database = conn.GetDatabase();
int count = (await database.ListRangeAsync(queueName)).Length;
if (count <= )
{
throw new Exception($"队列{queueName}数据为零");
}
string redisValue = await conn.GetDatabase().ListRightPopAsync(queueName);
if (!string.IsNullOrEmpty(redisValue))
return redisValue;
else
return string.Empty;
}
}
#endregion #endregion #region 分布式锁
public static void LockByRedis(string key, int expireTimeSeconds = )
{
try
{
IDatabase database1 = ConnectionMultiplexer.Connect(connectionRedisStr).GetDatabase();
while (true)
{
expireTimeSeconds = expireTimeSeconds > ? : expireTimeSeconds;
bool lockflag = database1.LockTake(key, Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds(expireTimeSeconds));
if (lockflag)
{
break;
}
}
}
catch (Exception ex)
{
throw new Exception($"Redis加锁异常:原因{ex.Message}");
}
} public static bool UnLockByRedis(string key)
{
ConnectionMultiplexer conn = ConnectionMultiplexer.Connect(connectionRedisStr);
try
{
IDatabase database1 = conn.GetDatabase();
return database1.LockRelease(key, Thread.CurrentThread.ManagedThreadId);
}
catch (Exception ex)
{
throw new Exception($"Redis加锁异常:原因{ex.Message}");
}
finally
{
if (conn != null)
{
conn.Close();
conn.Dispose();
}
}
}
#endregion }
}

 using System;
using System.Collections.Generic;
using System.Text; namespace RedisPublishAndSubHelper
{
using StackExchange.Redis;
using System.Net.Http;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks; public class MyRedisSubPublishHelper
{
private static readonly string redisConnectionStr = "12.32.12.54:6379,connectTimeout=10000,connectRetry=3,syncTimeout=10000";
private static readonly ConnectionMultiplexer connectionMultiplexer = null;
static MyRedisSubPublishHelper()
{
connectionMultiplexer = ConnectionMultiplexer.Connect(redisConnectionStr);
} #region 发布订阅
public void SubScriper(string topticName, Action<RedisChannel, RedisValue> handler = null)
{
ISubscriber subscriber = connectionMultiplexer.GetSubscriber();
ChannelMessageQueue channelMessageQueue = subscriber.Subscribe(topticName);
channelMessageQueue.OnMessage(channelMessage =>
{
if (handler != null)
{
string redisChannel = channelMessage.Channel;
string msg = channelMessage.Message;
handler.Invoke(redisChannel, msg);
}
else
{
string msg = channelMessage.Message;
Console.WriteLine($"订阅到消息: { msg},Channel={channelMessage.Channel}");
}
});
}
public void PublishMessage(string topticName, string message)
{
ISubscriber subscriber = connectionMultiplexer.GetSubscriber();
long publishLong = subscriber.Publish(topticName, message);
Console.WriteLine($"发布消息成功:{publishLong}");
}
#endregion #region 入队出队
public static async Task<long> EnqueueListLeftPushAsync(RedisKey queueName, RedisValue redisvalue)
{
return await connectionMultiplexer.GetDatabase().ListLeftPushAsync(queueName, redisvalue);
} public static async Task<string> DequeueListPopRightAsync(RedisKey queueName)
{
IDatabase database = connectionMultiplexer.GetDatabase();
int count = (await database.ListRangeAsync(queueName)).Length;
if (count <= )
{
throw new Exception($"队列{queueName}数据为零");
}
string redisValue = await database.ListRightPopAsync(queueName);
if (!string.IsNullOrEmpty(redisValue))
return redisValue;
else
return string.Empty;
}
#endregion #region 分布式锁
public static void LockByRedis(string key, int expireTimeSeconds = )
{
try
{
IDatabase database = connectionMultiplexer.GetDatabase();
while (true)
{
expireTimeSeconds = expireTimeSeconds > ? : expireTimeSeconds;
bool lockflag = database.LockTake(key, Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds(expireTimeSeconds));
if (lockflag)
{
break;
}
}
}
catch (Exception ex)
{
throw new Exception($"Redis加锁异常:原因{ex.Message}");
}
} public static bool UnLockByRedis(string key)
{
try
{
IDatabase database = connectionMultiplexer.GetDatabase();
return database.LockRelease(key, Thread.CurrentThread.ManagedThreadId);
}
catch (Exception ex)
{
throw new Exception($"Redis加锁异常:原因{ex.Message}");
}
}
#endregion
}
}

.NetCore使用Redis,StackExchange.Redis队列,发布与订阅,分布式锁的简单使用的更多相关文章

  1. redis集群+JedisCluster+lua脚本实现分布式锁(转)

    https://blog.csdn.net/qq_20597727/article/details/85235602 在这片文章中,使用Jedis clien进行lua脚本的相关操作,同时也使用一部分 ...

  2. StackExchange.Redis学习笔记(五) 发布和订阅

    Redis命令中的Pub/Sub Redis在 2.0之后的版本中 实现了 事件推送的  发布订阅命令 以下是Redis关于发布和订阅提供的相关命令 SUBSCRIBE channel [channe ...

  3. redis实现消息队列&发布/订阅模式使用

    在项目中用到了redis作为缓存,再学习了ActiveMq之后想着用redis实现简单的消息队列,下面做记录.   Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易的实现一个高性 ...

  4. .netcore里使用StackExchange.Redis TimeOut 情况解决方法

    在用StackExchange.Redis这个组件时候,时不时会出现异常TimeOut解决方法如下, 解决方法: 在Program的Main入口方法里添加一句话: System.Threading.T ...

  5. EF+Redis(StackExchange.Redis)实现分布式锁,自测可行

    电商平台 都会有抢购的情况,比如 1元抢购. 而抢购 最重要的 就是库存,很多情况下  库存处理不好,就会出现超卖现象. 本文将用redis为缓存,StackExchange 框架,消息队列方式 实现 ...

  6. Redis系列(八):发布与订阅

    Redis的发布与订阅,有点类似于消息队列,发送者往频道发送消息,频道的订阅者接收消息. 1. 发布与订阅示例 首先,在本机开启第1个Redis客户端,执行如下命令订阅blog.redis频道: SU ...

  7. Redis的n种妙用,分布式锁,分布式唯一id,消息队列,抽奖……

    介绍 redis是键值对的数据库,常用的五种数据类型为字符串类型(string),散列类型(hash),列表类型(list),集合类型(set),有序集合类型(zset) Redis用作缓存,主要两个 ...

  8. NodeJS操作Redis实现消息的发布与订阅

    首先先说一下流程: 1.保存数据到Redis,然后将member值publish到 chat频道(publish.js功能) 2.readRedis.js文件此前一直在监听chat频道,readRed ...

  9. 八十五:redis之redis的事物、发布和订阅操作 (2019-11-18 22:54)

    redis事物可以一次执行多个命令,事物具有以下特征1.隔离操作:事物中的所有命令都会序列化.按顺序执行,不会被其他命令打扰2.原子操作:事物中的命令要么全部被执行,要么全部都不执行 开启一个事物,以 ...

随机推荐

  1. JAVA实现BP神经网络算法

    工作中需要预测一个过程的时间,就想到了使用BP神经网络来进行预测. 简介 BP神经网络(Back Propagation Neural Network)是一种基于BP算法的人工神经网络,其使用BP算法 ...

  2. PHP tmpfile() 函数

    定义和用法 tmpfile() 函数以读写(w+)模式创建一个具有唯一文件名的临时文件. 语法 tmpfile() 提示和注释 注释:临时文件会在文件关闭后(用 fclose())或当脚本结束后自动被 ...

  3. EC R 86 D Multiple Testcases 构造 贪心 二分

    LINK:Multiple Testcases 得到很多种做法.其中O(n)的做法值得一提. 容易想到二分答案 check的时候发现不太清楚分配的策略. 需要先考虑如何分配 容易发现大的东西会对小的产 ...

  4. 2019 7 8 HL 模拟赛

    今天 很不爽 昨天晚上没有睡好觉 大约2点才睡着吧 反正翻来覆去睡不着 不知道为什么可能可行流 或者可行费用流并没有深刻理解 .我不会写 让我心情非常的焦躁. 大凶 顺理成章的被3位强者吊着锤(妈呀我 ...

  5. 实践录丨如何在鲲鹏服务器OpenEuler操作系统中快速部署OpenGauss数据库

    本文适合需要快速了解OpenGauss基本使用和操作的单机用户,可以短时间内完成安装体验.对于企业级生产使用或者需要部署多台服务器的,不适合本文. 因为业务需要,要在鲲鹏架构里安装单机版的OpenGa ...

  6. windows:shellcode生成框架和加载

    https://www.cnblogs.com/theseventhson/p/13194646.html  分享了shellcode 的基本原理,核心思路是动态获取GetProcAddress和Lo ...

  7. Ef Core增加Sql方法

    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)] public class DbFunAttribute : Attri ...

  8. ACL2020 Contextual Embeddings When Are They Worth It 精读

    上下文嵌入(Bert词向量): 什么时候值得用? ACL 2018 预训练词向量 (上下文嵌入Bert,上下文无关嵌入Glove, 随机)详细分析文章 1 背景 图1 Bert 优点 效果显著 缺点 ...

  9. 比PS还好用!Python 20行代码批量抠图

    你是否曾经想将某张照片中的人物抠出来,然后拼接到其他图片上去,从而可以即使你在天涯海角,我也可以到此一游? 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在 ...

  10. 用python分析1225万条淘宝数据,终于搞清楚了我的交易行为

    大家好,我是黄同学