如何在Golang中从Redis键值存储中获取一个值,该值是一个列表?

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

How to get a value which is a list from redis key-value store in golang?

问题

我正在使用golang编写一个函数,通过传递键来从Redis数据库中获取值。该值是一个列表。我正在使用"GET" Redis命令来获取该值。但是它给我返回了一个错误。

你可以在下面找到代码,

  1. func GetValue(key string) []string {
  2. var value []string
  3. var err error
  4. value, err = redis.Strings(conn.Do("GET", key))
  5. if err != nil {
  6. log.Fatal(err)
  7. }
  8. fmt.Println(value)
  9. return value
  10. }
  11. func RetrieveValue() {
  12. keyType, _ := conn.Do("TYPE", recentItemKey)
  13. fmt.Println("Type", keyType)
  14. var results []string
  15. results = GetValue(recentItemKey)
  16. for _, val := range results {
  17. fmt.Println(val)
  18. }
  19. }

以下是输出结果,

  1. Type list
  2. 2015/03/14 19:09:12 WRONGTYPE Operation against a key holding the wrong kind of value
  3. exit status 1

版本

Go 1.4.2
Redis-2.8.19

Redis Go库

github.com/garyburd/redigo/redis

有人可以帮我解决这个问题吗?谢谢。

英文:

I am writing a function in golang to get the value from redis db by passing the key. The value is a list. I am using 'GET' redis command to get the value. But it is giving me error.

You can find below the code,

  1. func GetValue(key string) []string {
  2. var value []string
  3. var err error
  4. value, err = redis.Strings(conn.Do("GET", key))
  5. if err != nil {
  6. log.Fatal(err)
  7. }
  8. fmt.Println(value)
  9. return value
  10. }
  11. func RetrieveValue() {
  12. keyType, _ := conn.Do("TYPE", recentItemKey)
  13. fmt.Println("Type", keyType)
  14. var results []string
  15. results = GetValue(recentItemKey)
  16. for _, val := range results {
  17. fmt.Println(val)
  18. }
  19. }

And the output is here,

  1. Type list
  2. 2015/03/14 19:09:12 WRONGTYPE Operation against a key holding the wrong kind of value
  3. exit status 1

Version

  1. Go 1.4.2
  2. Redis-2.8.19

Redis Go Library

  1. github.com/garyburd/redigo/redis

Could anyone help me on this.? Thank you

答案1

得分: 9

使用LRANGE命令获取列表的元素:

  1. func GetValues(key string) []string {
  2. value, err := redis.Strings(conn.Do("LRANGE", key, 0, -1))
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. return value
  7. }

GET命令用于获取字符串键的值。GET命令不能用于列表键。

英文:

Use LRANGE to get the elements of a list:

  1. func GetValues(key string) []string {
  2. value, err := redis.Strings(conn.Do("LRANGE", key, 0, -1))
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. return value
  7. }

The GET command gets the value of a string key. The GET command does not work on list keys.

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

发表评论

匿名网友

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

确定