Merge pull request #113 from go-redis/fix/better-pubsub-example

Rewrite PubSub example.
This commit is contained in:
Vladimir Mihailenco 2015-05-23 14:42:30 +03:00
commit fb9ea75a37
3 changed files with 32 additions and 11 deletions

View File

@ -83,7 +83,7 @@ var _ = Describe("Commands", func() {
Consistently(func() error { Consistently(func() error {
return client.Ping().Err() return client.Ping().Err()
}, "900ms").Should(HaveOccurred()) }, "400ms").Should(HaveOccurred()) // pause time - read timeout
Eventually(func() error { Eventually(func() error {
return client.Ping().Err() return client.Ping().Err()

View File

@ -2,7 +2,9 @@ package redis_test
import ( import (
"fmt" "fmt"
"net"
"strconv" "strconv"
"time"
"gopkg.in/redis.v3" "gopkg.in/redis.v3"
) )
@ -125,19 +127,37 @@ func ExamplePubSub() {
defer pubsub.Close() defer pubsub.Close()
err := pubsub.Subscribe("mychannel") err := pubsub.Subscribe("mychannel")
_ = err if err != nil {
panic(err)
}
msg, err := pubsub.Receive() err = client.Publish("mychannel", "hello").Err()
fmt.Println(msg, err) if err != nil {
panic(err)
}
pub := client.Publish("mychannel", "hello") for {
_ = pub.Err() 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() switch msg := msgi.(type) {
fmt.Println(msg, err) 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 <nil> // Output: subscribe mychannel
// Message<mychannel: hello> <nil> // mychannel hello
} }
func ExampleScript() { func ExampleScript() {

View File

@ -5,7 +5,8 @@ import (
"time" "time"
) )
// Not thread-safe. // PubSub implements Pub/Sub commands as described in
// http://redis.io/topics/pubsub.
type PubSub struct { type PubSub struct {
*baseClient *baseClient
} }