No F*cking Idea

Common answer to everything

Redis SETEX to the Rescue

| Comments

This is next mini entry about small thing that makes me happy in terms of changes in redis. Nothing new :D but still nice :D.

SET, EXPIRE, CHECK, ???, REPEAT

While using redis there is very common task we do. It is SET followed by EXPIRE. We do this when we want to cache for some period of time some data.

1
2
SET "user:1:token" "kuba"
EXPIRE "user:1:token" 5

This will set key user:1:token to value "kuba" and next set it to expire in 5 seconds. We can check Time to live on this key by using ttl command.

1
TTL "user:1:token"

this will return number of seconds that this key will be valid for or an negative number if its not valid anymore.

SETEX

SETEX Introduced in redis 2.0.0 command, lets you do both things SET and EXPIRE in one go. How do we use it ? Its simple!

1
SETEX <key> <seconds> <value>

It is not key, value seconds! :D:D example usage:

1
SETEX "key:to:home" 1500 "4b234ferg34ret34rasd32rs"

This will set for 1500 seconds key “key:to:home” to value “4b234ferg34ret34rasd32rs”. Pretty easy thing to do.

PSETEX

Since Redis 2.6.0 we can use new command it is PSETEX this is same as SETEX except it takes miliseconds not seconds so you can be more accurate in low latency / time situations

1
PSETEX "key:to:home" 15000 "4b234ferg34ret34rasd32rs"

Will set “key:to:home” to expire in 15 seconds, its important to notice that TTL will give you back amount of time units! so if you did PSETEX it will me miliseconds and if it is SETEX it is in seconds!.

Cheers!

Comments