redis分布式锁

1.高性能(分布式锁不能成为系统的性能瓶颈)
2.避免死锁(拿到锁的结点挂掉不会导致其它结点永远无法继续)
3.支持锁重入

 

事务

redis分布式锁
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"));
    }
redis分布式锁

 

并发锁(模拟2个线程同时并发)

redis分布式锁
   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()); } } } }
redis分布式锁

运行结果(刚开始有2个一样的数据,属于正常情况,自己想吧)

redis分布式锁


本文转自快乐就好博客园博客,原文链接:http://www.cnblogs.com/happyday56/p/3956486.html,如需转载请自行联系原作者
上一篇:SAP UI5应用访问OData metadata的url和Destination


下一篇:SQL SERVER 2014 下IF EXITS 居然引起执行计划变更的案例分享