Race status when using the Redis incr command and expires

Based on the redis document: http://redis.io/commands/incr

In the paragraph: Speed ​​limit 2 Shorter version code:

value = INCR (ip)

IF value == 1 THEN
  EXPIRE (ip, 1)

He argued that there was a race condition so that EXPIRE was never fulfilled. This means that the ip value can bounce from 0 to 2 in some way.

However, in my thoughts, since Redis is the only thread and INCR is a primitive command, shouldn't it be atomic by itself? Even if 2 clients do INCR almost at the same time, how can they extract 0 or both get 2?

+4
source share
3 answers

, redis , INCR , , EXPIRE. EXPIRE, > 1. redis . . . , 2 , . , .

+10

- , , : EVAL.

EVAL script, Lua Redis, , script .

script:

local v = redis.call('INCR', ARGV [1]), v == 1, redis.call('EXPIRE', ARGV [1], ARGV [2]) end return v

: INCR v, , v 1 ( ), , EXPIRE , v. ARGV [...] - , script, ARGV [1] - , ARGV [2] - - .

script:

> eval "local v = redis.call('INCR', ARGV [1]), v == 1, redis.call('EXPIRE', ARGV [1], ARGV [2]) end return v" 0 my_key 10

( ) 1

> eval "local v = redis.call('INCR', ARGV [1]), v == 1, redis.call('EXPIRE', ARGV [1], ARGV [2]) end return v" 0 my_key 10

( ) 2

> get my_key

"2"

[ 10 ]

> get my_key

()

+4

I met the same question, how about this: value = INCR (ip) IF [value == 1 || PTTL (ip) == -1] THEN EXPIRE (ip, 1)

If 2 clients do PTTL at almost the same time, get -1 and expire at almost the same time

+1
source

All Articles