Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set the expiry of the redis keys in golang

Tags:

redis

go

I am using golang as my backend.I am storing some token values in redis.I m setting the values HSET and getting the values in HGETALL.I would like to know if there is any function to set the expiry for the keys that i m storing in the redis database.i want the token and its data to be deleted after 1hour. I m using Redigo package for redis. Thanks.Appreciate any help.

I use this to set the struct with has token as key    
redisCon.Do("HMSET", redis.Args{}.Add(hashToken).AddFlat(&dataStruct)...)
like image 856
Rajesh Kumar Avatar asked Nov 18 '16 10:11

Rajesh Kumar


2 Answers

Redis documentation does not support a command like "HMSETEX". "HMSET" modifies the hashkeys and not the root key. TTL is supported at root key level and not at the hash key level. Hence, in your case you must be doing something like this in a separate call:

redisCon.Do("EXPIRE", key, ttl)

Which client are you using to connect to redis?

For redigo you can use this - https://github.com/yadvendar/redigo-wrapper In that use call

func Expire(RConn *redigo.Conn, key string, ttl int)

For goredis - https://godoc.org/gopkg.in/redis.v5#Client.TTL In this use:

func (c *Client) TTL(key string) *DurationCmd
like image 83
Yadvendar Avatar answered Nov 08 '22 05:11

Yadvendar


For those who use go-redis library, you can set expiration by calling

_, err = redisClient.Expire("my:redis:key", 1 * time.Hour).Result()

Alternatively, you can do that upon insertion

_, err = redisClient.Set("my:redis:key", "value", 1 * time.Hour).Result()
like image 42
Jossef Harush Kadouri Avatar answered Nov 08 '22 04:11

Jossef Harush Kadouri