redis 初步认识四(redis锁,防并发)
作者:互联网
using System; namespace ConsoleAppRedis { class Program { static void Main(string[] args) { //第一种,无登录密码 //var rds = new CSRedis.CSRedisClient("127.0.0.1:6379"); //rds.Set("test1", "123123", 60); //var str = rds.Get("test1"); //Console.WriteLine(str); //第二种 //RedisHelper.Initialization(rds); //RedisHelper.Set("aaaa", 11111); //var str1 = RedisHelper.Get("aaaa"); //Console.WriteLine(str1); //第三种,有登录密码 var rds2 = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123456,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍"); rds2.Set("test1", "123123", 60); var str3 = rds2.Get("test1"); Console.WriteLine(str3); //第四种,redis锁 #region redis 锁 var lockTimeout = 5000;//单位是毫秒 var currentTime = DateTime.Now.Ticks; //获取锁,才执行逻辑 if (SetNx("donationKey", currentTime + lockTimeout, lockTimeout)) { //dosomething Remove("donationKey"); //释放锁 } #endregion Console.WriteLine("Hello World!"); Console.ReadKey(); } #region redis 锁,防止并发同时捐步 private static bool SetNx(string key, long time, double expireMS) { if (RedisHelper.SetNx(key, time)) { if (expireMS > 0) RedisHelper.Expire(key, TimeSpan.FromMilliseconds(expireMS)); return true; } return false; } private static bool Remove(string key) { return RedisHelper.Del(key) > 0; } #endregion } }
标签:test1,Console,redis,初步,并发,key,var,RedisHelper 来源: https://www.cnblogs.com/ligenyun/p/10786854.html