我正在使用下面提到的代码从 Redis 发布-订阅中获取输出。在 Redis 期间传递的消息发布字符串 ()。test-message
但是,我在订阅阶段获得的输出是 类型 。以下是我在运行下面提到的代码时获得的输出(而不是预期的输出。[]uint8
[116 101 115 116 45 109 101 115 115 97 103 101]
test-message
这是由下面提到的代码中的此行引起的fmt.Println("Output: ", v.Data, reflect.TypeOf(v.Data)).
如何在上述行的“订阅”(即测试消息
)中获得我想要的正确输出?我觉得我可能需要从转换为以获得正确的输出。[]uint8
string
我的代码在下面给出。我用这个好的答案作为我的代码的参考。
package main
import (
"fmt"
"log"
"reflect"
"time"
"github.com/gomodule/redigo/redis"
)
func main() {
fmt.Println("Start redis test.")
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
log.Println(err)
} else {
log.Println("No error during redis.Dial.")
}
// defer c.Close()
val := "test-message"
/// Publisher.
go func() {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
panic(err)
}
count := 0
for {
c.Do("PUBLISH", "example", val)
// c.Do("PUBLISH", "example",
// fmt.Sprintf("test message %d", count))
count++
time.Sleep(1 * time.Second)
}
}()
/// End here
/// Subscriber.
psc := redis.PubSubConn{Conn: c}
psc.Subscribe("example")
for {
switch v := psc.Receive().(type) {
case redis.Message:
//fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
fmt.Println("Output: ", v.Data, reflect.TypeOf(v.Data))
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
fmt.Println(v)
}
time.Sleep(1)
}
/// End here
}
慕斯王
相关分类