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博客 ” ,链接:https://blog.itpub.net/301743/viewspace-733699/
,如需转载,请注明出处,否则将追究法律责任。