stackexchange.mysql_.NetCore使用Redis,StackExchange.Redis队列,发布与订阅,分布式锁的简单使用...

本文档展示了如何在.NetCore应用程序中使用StackExchange.Redis库进行Redis操作,包括设置和获取字符串、列表的入队和出队、以及实现分布式锁。此外,还提供了发布/订阅功能的基础使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Threading.Tasks;5

6 namespaceRedisPublishAndSubHelper7 {8 usingStackExchange.Redis;9 usingStackExchange;10 usingSystem.Threading;11

12 public classMyRedisHelper13 {14 private static readonly string connectionRedisStr = string.Empty;15 staticMyRedisHelper()16 {17 //在这里来初始化一些配置信息

18 connectionRedisStr = "12.23.45.12:6379,connectTimeout=1000,connectRetry=3,syncTimeout=10000";19 }20

21 #region Redis string简单的常见同步方法操作

22 public static bool StringSet(string key, string stringValue, double senconds = 60)23 {24 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))25 {26 IDatabase db =conn.GetDatabase();27 returndb.StringSet(key, stringValue, TimeSpan.FromSeconds(senconds));28 }29 }30 public static string StringGet(stringkey)31 {32 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))33 {34 IDatabase db =conn.GetDatabase();35 returndb.StringGet(key);36 }37 }38

39 public static long StringInc(stringkey)40 {41 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))42 {43 IDatabase db =conn.GetDatabase();44 returndb.StringIncrement(key);45 }46 }47

48 public static long StringDec(stringkey)49 {50 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))51 {52 IDatabase db =conn.GetDatabase();53 returndb.StringDecrement(key);54 }55 }56 public static bool KeyExists(stringkey)57 {58 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))59 {60 IDatabase db =conn.GetDatabase();61 returndb.KeyExists(key);62 }63 }64 #endregion

65

66 #region List Hash, Set,Zset 大同小异的使用,比较简单,后续有时间再补上

67

68 #endregion

69

70 #region 入队出队

71

72 #region 入队

73 ///

74 ///入队right75 ///

76 ///

77 ///

78 ///

79 public static longEnqueueListRightPush(RedisKey queueName, RedisValue redisValue)80 {81 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))82 {83 returnconn.GetDatabase().ListRightPush(queueName, redisValue);84 }85 }86 ///

87 ///入队left88 ///

89 ///

90 ///

91 ///

92 public static longEnqueueListLeftPush(RedisKey queueName, RedisValue redisvalue)93 {94 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))95 {96 returnconn.GetDatabase().ListLeftPush(queueName, redisvalue);97 }98 }99 ///

100 ///入队left异步101 ///

102 ///

103 ///

104 ///

105 public static async TaskEnqueueListLeftPushAsync(RedisKey queueName, RedisValue redisvalue)106 {107 using (var conn = awaitConnectionMultiplexer.ConnectAsync(connectionRedisStr))108 {109 return awaitconn.GetDatabase().ListLeftPushAsync(queueName, redisvalue);110 }111 }112 ///

113 ///获取队列的长度114 ///

115 ///

116 ///

117 public static longEnqueueListLength(RedisKey queueName)118 {119 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))120 {121 returnconn.GetDatabase().ListLength(queueName);122 }123 }124

125 #endregion

126

127 #region 出队

128 public static stringDequeueListPopLeft(RedisKey queueName)129 {130 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))131 {132 IDatabase database =conn.GetDatabase();133 int count =database.ListRange(queueName).Length;134 if (count <= 0)135 {136 throw new Exception($"队列{queueName}数据为零");137 }138 string redisValue =database.ListLeftPop(queueName);139 if (!string.IsNullOrEmpty(redisValue))140 returnredisValue;141 else

142 return string.Empty;143 }144 }145 public static stringDequeueListPopRight(RedisKey queueName)146 {147 using (var conn =ConnectionMultiplexer.Connect(connectionRedisStr))148 {149 IDatabase database =conn.GetDatabase();150 int count =database.ListRange(queueName).Length;151 if (count <= 0)152 {153 throw new Exception($"队列{queueName}数据为零");154 }155 string redisValue =conn.GetDatabase().ListRightPop(queueName);156 if (!string.IsNullOrEmpty(redisValue))157 returnredisValue;158 else

159 return string.Empty;160 }161 }162 public static async TaskDequeueListPopRightAsync(RedisKey queueName)163 {164 using (var conn = awaitConnectionMultiplexer.ConnectAsync(connectionRedisStr))165 {166 IDatabase database =conn.GetDatabase();167 int count = (awaitdatabase.ListRangeAsync(queueName)).Length;168 if (count <= 0)169 {170 throw new Exception($"队列{queueName}数据为零");171 }172 string redisValue = awaitconn.GetDatabase().ListRightPopAsync(queueName);173 if (!string.IsNullOrEmpty(redisValue))174 returnredisValue;175 else

176 return string.Empty;177 }178 }179 #endregion

180

181 #endregion

182

183 #region 分布式锁

184 public static void LockByRedis(string key, int expireTimeSeconds = 10)185 {186 try

187 {188 IDatabase database1 =ConnectionMultiplexer.Connect(connectionRedisStr).GetDatabase();189 while (true)190 {191 expireTimeSeconds = expireTimeSeconds > 20 ? 10: expireTimeSeconds;192 bool lockflag =database1.LockTake(key, Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds(expireTimeSeconds));193 if(lockflag)194 {195 break;196 }197 }198 }199 catch(Exception ex)200 {201 throw new Exception($"Redis加锁异常:原因{ex.Message}");202 }203 }204

205 public static bool UnLockByRedis(stringkey)206 {207 ConnectionMultiplexer conn =ConnectionMultiplexer.Connect(connectionRedisStr);208 try

209 {210 IDatabase database1 =conn.GetDatabase();211 returndatabase1.LockRelease(key, Thread.CurrentThread.ManagedThreadId);212 }213 catch(Exception ex)214 {215 throw new Exception($"Redis加锁异常:原因{ex.Message}");216 }217 finally

218 {219 if (conn != null)220 {221 conn.Close();222 conn.Dispose();223 }224 }225 }226 #endregion

227

228 }229 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值