zoukankan      html  css  js  c++  java
  • Redis锁的简单应用

    本文版权归博客园和作者本人吴双共同所有 。转载爬虫请注明地址,博客园蜗牛 http://www.cnblogs.com/tdws/p/5712835.html

    蜗牛Redis系列文章目录http://www.cnblogs.com/tdws/tag/NoSql/

    Redis Cluster http://www.cnblogs.com/tdws/p/7710545.html

    其实说多线程修改数据也不合适,毕竟redis服务端是单线程的,所有命令串行执行,只是在客户端并发发送命令的时候,导致串行的命令一些排列问题和网络时间差等造成数据不一致。本文虽然是数字的加减,但是为了说明锁的情况,故意不是用原子命令incr。也并非分布式锁的正确实现,没有考虑一些重入性等,稍后会整理一篇分布式锁的实践。

    Redis分布式锁 http://www.cnblogs.com/tdws/p/5808528.html

    ZK+curator 分布式锁 http://www.cnblogs.com/tdws/p/5874686.html

    先配上一个简易的RedisHelper,一个set值,一个get值,一个设置并发锁,以便在我后面的操作中,你能清楚我究竟做了什么。

     1  public class RedisHelper
     2     {
     3         public RedisClient client = new RedisClient("127.0.0.1", 6379);
     4         public void Set<T>(string key, T val)
     5         {
     6             client.Set(key, val);
     7         }
     8         public T Get<T>(string key)
     9         {
    10             var result = client.Get<T>(key);
    11             return result;
    12         }
    13         public IDisposable Acquire(string key)
    14         {
    15            return  client.AcquireLock(key);
    16         }
    17     }
    View Code

    下面看一下并发代码,我只new了两个Thread。两个线程同时想访问同一个key,分别访问五万次,在并发条件下,我们很难保证数据的准确性,请比较输出结果。

     1 static void Main(string[] args)
     2         {
     3             RedisHelper rds = new RedisHelper();
     4             rds.Set<int>("mykey1", 0);
     5             Thread myThread1 = new Thread(AddVal);
     6             Thread myThread2 = new Thread(AddVal);
     7             myThread1.Start();
     8             myThread2.Start();
     9             Console.WriteLine("等待两个线程结束");
    10             Console.ReadKey();
    11         }
    12 
    13         public static void AddVal()
    14         {
    15             RedisHelper rds = new RedisHelper();
    16             for (int i = 0; i < 50000; i++)
    17             {
    18                 
    19                     int result = rds.Get<int>("mykey1");
    20                     rds.Set<int>("mykey1", result + 1);
    21                 
    22             }
    23             Console.WriteLine("线程结束,输出" + rds.Get<int>("mykey1"));
    24         }
    View Code

    是的,和我们单线程,跑两个50000,会输出100000。现在是两个并发线程同时跑在由于并发造成的数据结果往往不是我们想要的。那么如何解决这个问题呢,Redis已经为我们准备好了!

    你可以看到我RedisHelper中有个方法是 public IDisposable Acquire(string key)。  也可以看到他返回的是IDisposable,证明我们需要手动释放资源。方法内部的 AcquireLock正是关键之处,它像redis中索取一把锁头,被锁住的资源,只能被单个线程访问,不会被两个线程同时get或者set,这两个线程一定是交替着进行的,当然这里的交替并不是指你一次我一次,也可能是你多次,我一次,下面看代码。

     1  static void Main(string[] args)
     2         {
     3             RedisHelper rds = new RedisHelper();
     4             rds.Set<int>("mykey1", 0);
     5             Thread myThread1 = new Thread(AddVal);
     6             Thread myThread2 = new Thread(AddVal);
     7             myThread1.Start();
     8             myThread2.Start();
     9             Console.WriteLine("等待两个线程结束");
    10             Console.ReadKey();
    11         }
    12 
    13         public static void AddVal()
    14         {
    15             RedisHelper rds = new RedisHelper();
    16             for (int i = 0; i < 50000; i++)
    17             {
    18                 using (rds.Acquire("lock"))
    19                 {
    20                     int result = rds.Get<int>("mykey1");
    21                     rds.Set<int>("mykey1", result + 1);
    22                 }
    23             }
    24             Console.WriteLine("线程结束,输出" + rds.Get<int>("mykey1"));
    25         }
    View Code

    可以看到我使用了using,调用我的Acquire方法获取锁。

    输出结果最后是100000,正是我们要的正确结果。前面的8W+是因为两个线程之一先执行结束了。

    还有,在正式使用的过程中,建议给我们的锁,使用后删除掉,并加上一个过期时间,使用expire。

    以免程序执行期间意外退出,导致锁一直存在,今后可能无法更新或者获取此被锁住的数据。

    你也可以尝试一下不设置expire,在程序刚开始执行时,关闭console,重新运行程序,并且在redis-cli的操作控制台,get你锁住的值,将会永远获取不到。

    所有连接此redis实例的机器,同一时刻,只能有一个获取指定name的锁.

    下面是StackExchange.Redis的写法

     1            var info = "name-"+Environment.MachineName;
     2             //如果5秒不释放锁 自动释放。避免死锁
     3             if (db.LockTake("name", info, TimeSpan.FromSeconds(5)))
     4             {
     5                 try
     6                 {
     7                    
     8                 }
     9                 catch (Exception ex)
    10                 {
    11                     
    12                 }
    13                 finally
    14                 {
    15                    
    16                     db.LockRelease("name", token);
    17                 }
    18             }
  • 相关阅读:
    668. Kth Smallest Number in Multiplication Table
    658. Find K Closest Elements
    483. Smallest Good Base
    475. Heaters
    454. 4Sum II
    441. Arranging Coins
    436. Find Right Interval
    410. Split Array Largest Sum
    392. Is Subsequence
    378. Kth Smallest Element in a Sorted Matrix
  • 原文地址:https://www.cnblogs.com/tdws/p/5712835.html
Copyright © 2011-2022 走看看