1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package main
import ( "context" "fmt" "github.com/go-redis/redis/v8" "time" )
func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, })
ctx := context.Background()
pubsub := rdb.Subscribe(ctx, "my-channel")
if _, err := pubsub.Receive(ctx); err != nil { panic(err) }
if err := rdb.Publish(ctx, "my-channel", "hello").Err(); err != nil { panic(err) }
time.AfterFunc(time.Second, func() { _ = pubsub.Close() })
ch := pubsub.Channel()
for msg := range ch { fmt.Println(msg.Channel, msg.Payload) } }
|