redis/pubsub.go

104 lines
1.8 KiB
Go
Raw Normal View History

2012-07-25 17:00:50 +04:00
package redis
import (
"fmt"
2012-08-05 16:09:43 +04:00
"sync"
2012-07-25 17:00:50 +04:00
)
type PubSubClient struct {
*Client
2012-08-05 16:09:43 +04:00
conn *Conn
ch chan *Message
once sync.Once
2012-07-25 17:00:50 +04:00
}
2012-08-05 16:09:43 +04:00
func newPubSubClient(client *Client) (*PubSubClient, error) {
conn, _, err := client.ConnPool.Get()
if err != nil {
return nil, err
}
2012-07-25 17:00:50 +04:00
c := &PubSubClient{
2012-08-05 16:09:43 +04:00
Client: client,
conn: conn,
2012-07-25 17:00:50 +04:00
ch: make(chan *Message),
}
2012-08-05 16:09:43 +04:00
return c, nil
2012-07-25 17:00:50 +04:00
}
type Message struct {
Name, Channel, Message string
Number int64
Err error
}
func (c *PubSubClient) consumeMessages() {
req := NewMultiBulkReq()
for {
// Replies can arrive in batches.
// Read whole reply and parse messages one by one.
2012-07-26 22:43:21 +04:00
2012-08-05 16:09:43 +04:00
err := c.ReadReply(c.conn)
2012-07-25 17:00:50 +04:00
if err != nil {
msg := &Message{}
msg.Err = err
c.ch <- msg
return
}
for {
msg := &Message{}
2012-08-05 16:09:43 +04:00
replyI, err := req.ParseReply(c.conn.Rd)
2012-07-25 17:00:50 +04:00
if err != nil {
msg.Err = err
c.ch <- msg
break
}
2012-07-26 22:43:21 +04:00
reply := replyI.([]interface{})
2012-07-25 17:00:50 +04:00
msgName := reply[0].(string)
switch msgName {
case "subscribe", "unsubscribe":
msg.Name = msgName
msg.Channel = reply[1].(string)
msg.Number = reply[2].(int64)
case "message":
msg.Name = msgName
msg.Channel = reply[1].(string)
msg.Message = reply[2].(string)
default:
msg.Err = fmt.Errorf("Unsupported message name: %q.", msgName)
}
c.ch <- msg
2012-08-05 16:09:43 +04:00
if !c.conn.Rd.HasUnread() {
2012-07-25 17:00:50 +04:00
break
}
}
}
}
func (c *PubSubClient) Subscribe(channels ...string) (chan *Message, error) {
args := append([]string{"SUBSCRIBE"}, channels...)
req := NewMultiBulkReq(args...)
2012-08-05 16:09:43 +04:00
if err := c.WriteReq(req.Req(), c.conn); err != nil {
2012-07-25 17:00:50 +04:00
return nil, err
}
2012-08-05 16:09:43 +04:00
c.once.Do(func() {
2012-07-25 17:00:50 +04:00
go c.consumeMessages()
2012-08-05 16:09:43 +04:00
})
2012-07-25 17:00:50 +04:00
return c.ch, nil
}
func (c *PubSubClient) Unsubscribe(channels ...string) error {
args := append([]string{"UNSUBSCRIBE"}, channels...)
req := NewMultiBulkReq(args...)
2012-08-05 16:09:43 +04:00
return c.WriteReq(req.Req(), c.conn)
2012-07-25 17:00:50 +04:00
}