在使用Golang时,将单次使用记录存储在Redis中的最佳方式是什么?

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

best way to store a single time use record in redis using golang

问题

我正在使用golang和go-redis包。
我想在Redis中存储一个键值对(例如一次性令牌)。当读取此令牌时,我会生成一个永久令牌。但是一次性令牌应该在读取值后被删除,以避免快速重放攻击。实现这个的最佳方法是什么?我一直在考虑使用互斥锁。

英文:

I am using golang and go-redis package
I would like to store a key-value pair in redis (e.g one time token). When this token is read, I generate a permanent token. But the one time token should be deleted once I have read the value. This is to avoid fast-replay attack. What is the best way to implement this. I have been thinking of mutex.

答案1

得分: 3

这是MULTI-EXEC功能的完美使用案例:

MULTI
GET key
DELETE key
EXEC

或者在Go语言中:

pipe := client.TxPipeline()

get := pipe.Get("key")
pipe.Del("key")

_, err := pipe.Exec()
fmt.Println(get.Val(), err)

这将确保这两个命令在一个事务中执行,因此要么获取并删除键,要么根本不获取。

英文:

This is a perfect use case for the MULTI-EXEC functionality:

MULTI
GET key
DELETE key
EXEC

Or in go:

pipe := client.TxPipeline()

get := pipe.Get("key")
pipe.Del("key")

_, err := pipe.Exec()
fmt.Println(get.Val(), err)

This will ensure that both commands execute in a transaction, so the key will either be retrieved and deleted or not retrieved at all.

huangapple
  • 本文由 发表于 2017年6月20日 22:38:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/44656095.html
匿名

发表评论

匿名网友

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

确定