A Couple Redis Gotchas with a Focus on Concurrency

jieforest發表於2012-06-25
Redis is an amazing global datastructure server. The fact that it’s global, makes it ideal for a multi-process or multi-threaded system, to get some concurrency action going. This also means, that a lot of the cautions that need to be taken while working in a shared memory system also apply to a situation where redis is operating in a concurrent/distributed environment.

In this article, I am going to glaze over a couple of gotcha’s to watch out for when working with Redis. It is by no means an attempt to be an exhaustive monograph on concurrency and Redis, but rather something to get your feet wet.

Having the rug pulled from under you

Check out the following code:

CODE:

1.if redis.exists("some_key")
2.puts "Yay! Redis' got it"
3.compute_primes   #Perform. some time-intensive computation
4.val = redis.get("some_key")
5.render :json => { :value => val }
6.endThis code that checks for the existence of a key in redis in line 1 and then performs some conditional logic, part of which involves retrieving the key from redis has a race condition in it. It is the fact that in between lines 1 and 4 another process could’ve deleted the key from redis. A quick fix for this:

CODE:

1.if val = redis.get("some_key")
2.#rest of the code here ...
3.end

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-733699/,如需轉載,請註明出處,否則將追究法律責任。

相關文章