Platinum Partner
architects,high-perf,performance,tips and tricks,redis

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:

 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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}