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
2:
3: open System
4: open ServiceStack.Redis
5:
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: }
15:
16: let ``should be able to save and retrieve from redis`` () =
17:
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 lockfor 2
Disposing of lockfor 2
Aquired lockfor 6
Disposing of lockfor 6
Aquired lockfor 0
Disposing of lockfor 0
Aquired lockfor 7
Disposing of lockfor 7
Aquired lockfor 9
Disposing of lockfor 9
Aquired lockfor 5
Disposing of lockfor 5
Aquired lockfor 3
Disposing of lockfor 3
Aquired lockfor 8
Disposing of lockfor 8
Aquired lockfor 1
Disposing of lockfor 1
Aquired lockfor 4
Disposing of lockfor 4
Beautifully serialized access from parallel processes. Very nice.