From f79308a137ef4bd4cd88d786184b3ae4ad48e1e4 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sat, 23 May 2015 14:15:05 +0300 Subject: [PATCH] Rewrite PubSub example. --- example_test.go | 38 +++++++++++++++++++++++++++++--------- pubsub.go | 3 ++- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/example_test.go b/example_test.go index 859b6458..fb63ecb8 100644 --- a/example_test.go +++ b/example_test.go @@ -2,7 +2,9 @@ package redis_test import ( "fmt" + "net" "strconv" + "time" "gopkg.in/redis.v3" ) @@ -125,19 +127,37 @@ func ExamplePubSub() { defer pubsub.Close() err := pubsub.Subscribe("mychannel") - _ = err + if err != nil { + panic(err) + } - msg, err := pubsub.Receive() - fmt.Println(msg, err) + err = client.Publish("mychannel", "hello").Err() + if err != nil { + panic(err) + } - pub := client.Publish("mychannel", "hello") - _ = pub.Err() + for { + msgi, err := pubsub.ReceiveTimeout(100 * time.Millisecond) + if err != nil { + if neterr, ok := err.(net.Error); ok && neterr.Timeout() { + // There are no more messages to process. Stop. + break + } + panic(err) + } - msg, err = pubsub.Receive() - fmt.Println(msg, err) + switch msg := msgi.(type) { + case *redis.Subscription: + fmt.Println(msg.Kind, msg.Channel) + case *redis.Message: + fmt.Println(msg.Channel, msg.Payload) + default: + panic(fmt.Sprintf("unknown message: %#v", msgi)) + } + } - // Output: subscribe: mychannel - // Message + // Output: subscribe mychannel + // mychannel hello } func ExampleScript() { diff --git a/pubsub.go b/pubsub.go index 5a32220b..9d63e6be 100644 --- a/pubsub.go +++ b/pubsub.go @@ -5,7 +5,8 @@ import ( "time" ) -// Not thread-safe. +// PubSub implements Pub/Sub commands as described in +// http://redis.io/topics/pubsub. type PubSub struct { *baseClient }