redis分布式锁
1.高性能(分布式锁不能成为系统的性能瓶颈)
2.避免死锁(拿到锁的结点挂掉不会导致其它结点永远无法继续)
3.支持锁重入
事务
using (IRedisClient RClient = prcm.GetClient()) { RClient.Add("key",1); using (IRedisTransaction IRT = RClient.CreateTransaction()) { IRT.QueueCommand(r => r.Set("key", 20)); IRT.QueueCommand(r => r.Increment("key",1)); IRT.Commit(); // 提交事务 } Response.Write(RClient.Get<string>("key")); }
并发锁(模拟2个线程同时并发)
public static bool SetLock(string key, int val, TimeSpan timeOut) { using (IRedisClient rds = prcm.GetClient()) { using (rds.AcquireLock("Lock" + key, timeOut)) { int v = rds.Get<int>(key); return rds.Set<int>(key, v + val); } } } using ServiceStack.Redis; using ServiceStack.Redis.Generic; using ServiceStack.Text; using Sim.Common; using System.Threading; namespace ConsoleTest { class Program { static void Main(string[] args) {
//启动2进程模拟 redis并发锁情况 Redis.Set<int>("u", 1); RedisConcurrence r1 = new RedisConcurrence("T1"); Thread thread1 = new Thread(new ThreadStart(r1.Go)); thread1.Start(); RedisConcurrence r2 = new RedisConcurrence("T2"); Thread thread2 = new Thread(new ThreadStart(r2.Go)); thread2.Start(); } } public class RedisConcurrence { private string key = "u"; /// <summary> /// 操作次数 /// </summary> private int count = 10; /// <summary> /// 锁定时间(秒) /// </summary> private int lockTime = 5; private string name; public string Name { get { return name; } set { name = value; } } public RedisConcurrence(string name) { this.name = name; } public void Go() { TimeSpan time = new TimeSpan(0, 0, 0, this.lockTime); for (var i = 0; i < this.count; i++) { Redis.SetLock(key, 1, time); Console.WriteLine(this.name + ":" + DateTime.Now.ToString() + " " + Redis.Get<int>(key).ToString()); } } } }
运行结果(刚开始有2个一样的数据,属于正常情况,自己想吧)