Over a million developers have joined DZone.

Redis: Very Useful As a Distributed Lock

DZone 's Guide to

Redis: Very Useful As a Distributed Lock

· Performance Zone ·
Free Resource

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 
         printfn "Disposing of lock for %i" n
 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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}