Tuesday, June 18, 2013

Redis: Very Useful As a Distributed Lock

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:

   1: module Zorrillo.Runtime.ProxyAutomation.Tests.RedisSpike
   3: open System
   4: open ServiceStack.Redis
   6: let iTakeALock n = 
   7:     async {
   8:         use redis = new RedisClient("redis.local")
   9:         let lock = redis.AcquireLock("integration_test_lock", TimeSpan.FromSeconds(10.0))
  10:         printfn "Aquired lock for %i" n 
  11:         Threading.Thread.Sleep(100)
  12:         printfn "Disposing of lock for %i" n
  13:         lock.Dispose()
  14:     }
  16: let ``should be able to save and retrieve from redis`` () =
  18:     [for i in [0..9] -> iTakeALock i]
  19:         |> Async.Parallel
  20:         |> 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.

1 comment:

Anonymous said...

Redis is conceptually so simple, but very easy to use across all kinds of distributed systems. From queues to caching to all kinds of uses, Redis is one of my favorite little pieces of software.