你是否正确使用了redigo的HDEL方法?

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

Am I using redigo HDEL correctly?

问题

我似乎对使用HDEL命令接口的用法有所了解,但似乎删除了0条记录。我是否漏掉了什么?

以下是有用的代码片段:

这个不起作用:

keysToDeleteArr []string //这个数组包含了要删除的有效键值

s.transClient.Do("MULTI")
_, err := s.transClient.Do("HDEL", myhash, keysToDeleteArr)
s.transClient.Do("EXEC")

输出结果为(int64) 0 // 删除的键的数量

这个起作用:

s.transClient.Do("MULTI")
for _, keyToDelete := range keysToDeleteArr {
  _, err := s.transClient.Do("HDEL", myhash, keyToDelete)
}
s.transClient.Do("EXEC")

输出结果为(int64) 1,对于每个HDEL操作都是如此。根据文档和对redigo库的静态代码分析,似乎切片是fields参数的可接受类型。

英文:

I seem to have the correct usage for using the HDEL command interface, but seem to get 0 records deleted. Am I missing something here?

Here are useful code snippets:

This doesn't work:

keysToDeleteArr []string //this has valid key values from upstream

s.transClient.Do("MULTI")
_, err := s.transClient.Do("HDEL", myhash, keysToDeleteArr)
s.transClient.Do("EXEC")

Gives an output (int64) 0 // # of keys deleted

This does work:

s.transClient.Do("MULTI")
for _, keyToDelete := range keysToDeleteArr {
  _, err := s.transClient.Do("HDEL", myhash, keyToDelete)
}
s.transClient.Do("EXEC")

Gives an output (int64) 1 for each HDEL. From the documentation and from static code analysis on the redigo lib, does seem like slices are acceptable parameters for fields

答案1

得分: 2

构建一个包含命令参数的[]interface{}。将interface{}的切片作为可变参数传递给Do方法:

args := make([]interface{}, 0, len(keysToDeleteArr) + 1)
args = append(args, myhash)
for _, v := range keysToDeleteArr {
    args = append(args, v)
}
_, err := s.transClient.Do("HDEL", args...)

使用Redigo的Args在一行中执行上述代码:

_, err := s.transClient.Do("HDEL", redis.Args{}.Add(myhash).AddFlat(keysToDeleteArr)...)
英文:

Construct an []interface{} containing the command arguments. Pass the slice of interface{} to the Do method as a variadic argument:

args := make([]interface{}, 0, len(keysToDeleteArr) + 1)
args = append(args, myhash)
for _, v := range keysToDeleteArr {
    args = append(args, v)
}
 _, err := s.transClient.Do("HDEL", args...)

Use Redigo's Args to execute the code above in a single line:

 _, err := s.transClient.Do("HDEL", redis.Args{}.Add(myhash).AddFlat(keysToDeleteArr)...)

huangapple
  • 本文由 发表于 2021年10月19日 08:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/69624009.html
匿名

发表评论

匿名网友

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

确定