Performance Zone is brought to you in partnership with:

Mike Hadlow is a Brighton, UK based developer, blogger and author of a number of open source frameworks and applications. Mike is a DZone MVB and is not an employee of DZone and has posted 88 posts at DZone. You can read more from them at their website. View Full User Profile

Redis: Very Useful As a Distributed Lock

06.18.2013
| 2452 views |
  • submit to reddit

In a Service Oriented Architecture you sometimes need a distributed lock; an application lock across many servers to serialize access to some constrained resource. I’ve been looking at using Redis, via the excellent ServiceStack.Redis client library, for this.

It really is super simple. Here’s a little F# sample to show it in action:

 module Zorrillo.Runtime.ProxyAutomation.Tests.RedisSpike
  
 open System
 open ServiceStack.Redis
  
 let iTakeALock n = 
     async {
         use redis = new RedisClient("redis.local")
         let lock = redis.AcquireLock("integration_test_lock", TimeSpan.FromSeconds(10.0))
         printfn "Aquired lock for %i" n 
         Threading.Thread.Sleep(100)
         printfn "Disposing of lock for %i" n
         lock.Dispose()
     }
  
 let ``should be able to save and retrieve from redis`` () =

 
     [for i in [0..9] -> iTakeALock i]
         |> Async.Parallel
         |> Async.RunSynchronously

The iTakeALock function creates an async task that uses the SeviceStack.Redis AquireLock function. It then pretends to do some work (Thread.Sleep(100)), and then releases the lock (lock.Dispose()).

Running 10 iTakeALocks in parallel (line 16 onwards) gives the following result:

Aquired lock for 2
Disposing of lock for 2
Aquired lock for 6
Disposing of lock for 6
Aquired lock for 0
Disposing of lock for 0
Aquired lock for 7
Disposing of lock for 7
Aquired lock for 9
Disposing of lock for 9
Aquired lock for 5
Disposing of lock for 5
Aquired lock for 3
Disposing of lock for 3
Aquired lock for 8
Disposing of lock for 8
Aquired lock for 1
Disposing of lock for 1
Aquired lock for 4
Disposing of lock for 4

Beautifully serialized access from parallel processes. Very nice.

Published at DZone with permission of Mike Hadlow, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)