Parcourir la source

Add PING/PONG support to PubSubConn

Fixes #121
Gary Burd il y a 10 ans
Parent
commit
3e4727f0ef
2 fichiers modifiés avec 28 ajouts et 6 suppressions
  1. 21 6
      redis/pubsub.go
  2. 7 0
      redis/pubsub_test.go

+ 21 - 6
redis/pubsub.go

@@ -14,9 +14,7 @@
 
 package redis
 
-import (
-	"errors"
-)
+import "errors"
 
 // Subscription represents a subscribe or unsubscribe notification.
 type Subscription struct {
@@ -54,6 +52,11 @@ type PMessage struct {
 	Data []byte
 }
 
+// Pong represents a pubsub pong notification.
+type Pong struct {
+	Data string
+}
+
 // PubSubConn wraps a Conn with convenience methods for subscribers.
 type PubSubConn struct {
 	Conn Conn
@@ -90,9 +93,15 @@ func (c PubSubConn) PUnsubscribe(channel ...interface{}) error {
 	return c.Conn.Flush()
 }
 
-// Receive returns a pushed message as a Subscription, Message, PMessage or
-// error. The return value is intended to be used directly in a type switch as
-// illustrated in the PubSubConn example.
+// Ping sends a PING to the server with the specified data.
+func (c PubSubConn) Ping(data string) error {
+	c.Conn.Send("PING", data)
+	return c.Conn.Flush()
+}
+
+// Receive returns a pushed message as a Subscription, Message, PMessage, Pong
+// or error. The return value is intended to be used directly in a type switch
+// as illustrated in the PubSubConn example.
 func (c PubSubConn) Receive() interface{} {
 	reply, err := Values(c.Conn.Receive())
 	if err != nil {
@@ -124,6 +133,12 @@ func (c PubSubConn) Receive() interface{} {
 			return err
 		}
 		return s
+	case "pong":
+		var p Pong
+		if _, err := Scan(reply, &p.Data); err != nil {
+			return err
+		}
+		return p
 	}
 	return errors.New("redigo: unknown pubsub notification")
 }

+ 7 - 0
redis/pubsub_test.go

@@ -140,4 +140,11 @@ func TestPushed(t *testing.T) {
 
 	pc.Do("PUBLISH", "c1", "hello")
 	expectPushed(t, c, "PUBLISH c1 hello", redis.Message{Channel: "c1", Data: []byte("hello")})
+
+	c.Ping("hello")
+	expectPushed(t, c, `Ping("hello")`, redis.Pong{"hello"})
+
+	c.Conn.Send("PING")
+	c.Conn.Flush()
+	expectPushed(t, c, `Send("PING")`, redis.Pong{})
 }