INCR and EXPIRE at the same time in Redis?

7,903 views
Skip to first unread message

poiuytrez

unread,
Feb 25, 2016, 11:53:47 AM2/25/16
to Redis DB
Hello, 

Is there a way to have an equivalent of SETEX for INCR? I would like to increment a value and set an expiration date at the same time. 

Thank you for your help,
poiuytrez

Jan-Erik Rediger

unread,
Feb 25, 2016, 12:04:02 PM2/25/16
to redi...@googlegroups.com
MULTI
INCR yourkey
EXPIRE yourkey 100
EXEC

On Thu, Feb 25, 2016 at 08:53:47AM -0800, poiuytrez wrote:
> Hello,
>
> Is there a way to have an equivalent of SETEX
> <http://redis.io/commands/setex> for INCR? I would like to increment a
> value and set an expiration date at the same time.
>
> Thank you for your help,
> poiuytrez
>
> --
> You received this message because you are subscribed to the Google Groups "Redis DB" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to redis-db+u...@googlegroups.com.
> To post to this group, send email to redi...@googlegroups.com.
> Visit this group at https://groups.google.com/group/redis-db.
> For more options, visit https://groups.google.com/d/optout.

Itamar Haber

unread,
Feb 25, 2016, 1:26:39 PM2/25/16
to Redis DB, Jan-Erik Rediger

Or with Lua:

EVAL "redis.call('EXPIRE', KEYS[1], ARGV[1]) return redis.call('INCR', KEYS[1])" 1 yourkey 100

Marc Gravell

unread,
Feb 25, 2016, 4:07:33 PM2/25/16
to redi...@googlegroups.com

Minor point on the Lua example: "incr, expire" may give a slightly different result to "expire, incr" - in the case where the key does not currently exist. I would recommend "incr, expire", but this may require storing the value in a local (presumably it is incr that you want the reply of)

Itamar Haber

unread,
Feb 25, 2016, 4:20:26 PM2/25/16
to Redis DB
Thanks Mark, good point. v2.0:

EVAL "local r = redis.call('INCR', KEYS[1]) redis.call('EXPIRE', KEYS[1], ARGV[1]) return r" 1 yourkey 100

Itamar Haber | Chief Developer Advocate
Redis Watch Newsletter | Curator and Janitor
Redis Labs | ~ of Redis

Mobile: +1 (415) 688 2443
Office: +1 (650) 461 4652
Mobile (IL): +972 (54) 567 9692
Office (IL): +972 (3) 720 8515 Ext. 123
Email: ita...@redislabs.com
Twitter: @itamarhaber
Skype: itamar.haber

Blog  |  Twitter  |  LinkedIn


Reply all
Reply to author
Forward
0 new messages