如何在Golang中设置Redis键的过期时间

huangapple go评论69阅读模式
英文:

how to set the expiry of the redis keys in golang

问题

我正在使用golang作为我的后端语言。我将一些令牌值存储在Redis中。我使用HSET设置值,并使用HGETALL获取值。我想知道是否有函数可以为我在Redis数据库中存储的键设置过期时间。我希望在1小时后删除令牌及其数据。我正在使用Redigo包来操作Redis。谢谢!感谢任何帮助。

我使用以下代码将结构体设置为具有令牌作为键:
redisCon.Do("HMSET", redis.Args{}.Add(hashToken).AddFlat(&dataStruct)...)

英文:

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)...)

答案1

得分: 10

对于使用go-redis库的用户,您可以通过调用以下代码来设置过期时间:

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

或者,在插入时进行设置:

_, err = redisClient.Set("my:redis:key", "value", 1 * time.Hour).Result()
英文:

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()

答案2

得分: 6

Redis文档不支持像"HMSETEX"这样的命令。
"HMSET"修改的是哈希键而不是根键。TTL是在根键级别上支持的,而不是在哈希键级别上支持的。因此,在你的情况下,你可能需要使用单独的调用来执行以下操作:

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

你正在使用哪个客户端连接到Redis?

对于redigo,你可以使用这个 - https://github.com/yadvendar/redigo-wrapper
在其中使用以下调用:

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

对于goredis - https://godoc.org/gopkg.in/redis.v5#Client.TTL
在其中使用:

func (c *Client) TTL(key string) *DurationCmd
英文:

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

huangapple
  • 本文由 发表于 2016年11月18日 18:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/40674920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定