pubsub_example_test.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis_test
  15. import (
  16. "context"
  17. "fmt"
  18. "time"
  19. "github.com/garyburd/redigo/redis"
  20. )
  21. // listenPubSubChannels listens for messages on Redis pubsub channels. The
  22. // onStart function is called after the channels are subscribed. The onMessage
  23. // function is called for each message.
  24. func listenPubSubChannels(ctx context.Context, redisServerAddr string,
  25. onStart func() error,
  26. onMessage func(channel string, data []byte) error,
  27. channels ...string) error {
  28. // A ping is set to the server with this period to test for the health of
  29. // the connection and server.
  30. const healthCheckPeriod = time.Minute
  31. c, err := redis.Dial("tcp", redisServerAddr,
  32. // Read timeout on server should be greater than ping period.
  33. redis.DialReadTimeout(healthCheckPeriod+10*time.Second),
  34. redis.DialWriteTimeout(10*time.Second))
  35. if err != nil {
  36. return err
  37. }
  38. defer c.Close()
  39. psc := redis.PubSubConn{Conn: c}
  40. if err := psc.Subscribe(redis.Args{}.AddFlat(channels)...); err != nil {
  41. return err
  42. }
  43. done := make(chan error, 1)
  44. // Start a goroutine to receive notifications from the server.
  45. go func() {
  46. for {
  47. switch n := psc.Receive().(type) {
  48. case error:
  49. done <- n
  50. return
  51. case redis.Message:
  52. if err := onMessage(n.Channel, n.Data); err != nil {
  53. done <- err
  54. return
  55. }
  56. case redis.Subscription:
  57. switch n.Count {
  58. case len(channels):
  59. // Notify application when all channels are subscribed.
  60. if err := onStart(); err != nil {
  61. done <- err
  62. return
  63. }
  64. case 0:
  65. // Return from the goroutine when all channels are unsubscribed.
  66. done <- nil
  67. return
  68. }
  69. }
  70. }
  71. }()
  72. ticker := time.NewTicker(healthCheckPeriod)
  73. defer ticker.Stop()
  74. loop:
  75. for err == nil {
  76. select {
  77. case <-ticker.C:
  78. // Send ping to test health of connection and server. If
  79. // corresponding pong is not received, then receive on the
  80. // connection will timeout and the receive goroutine will exit.
  81. if err = psc.Ping(""); err != nil {
  82. break loop
  83. }
  84. case <-ctx.Done():
  85. break loop
  86. case err := <-done:
  87. // Return error from the receive goroutine.
  88. return err
  89. }
  90. }
  91. // Signal the receiving goroutine to exit by unsubscribing from all channels.
  92. psc.Unsubscribe()
  93. // Wait for goroutine to complete.
  94. return <-done
  95. }
  96. func publish() {
  97. c, err := dial()
  98. if err != nil {
  99. fmt.Println(err)
  100. return
  101. }
  102. defer c.Close()
  103. c.Do("PUBLISH", "c1", "hello")
  104. c.Do("PUBLISH", "c2", "world")
  105. c.Do("PUBLISH", "c1", "goodbye")
  106. }
  107. // This example shows how receive pubsub notifications with cancelation and
  108. // health checks.
  109. func ExamplePubSubConn() {
  110. redisServerAddr, err := serverAddr()
  111. if err != nil {
  112. fmt.Println(err)
  113. return
  114. }
  115. ctx, cancel := context.WithCancel(context.Background())
  116. err = listenPubSubChannels(ctx,
  117. redisServerAddr,
  118. func() error {
  119. // The start callback is a good place to backfill missed
  120. // notifications. For the purpose of this example, a goroutine is
  121. // started to send notifications.
  122. go publish()
  123. return nil
  124. },
  125. func(channel string, message []byte) error {
  126. fmt.Printf("channel: %s, message: %s\n", channel, message)
  127. // For the purpose of this example, cancel the listener's context
  128. // after receiving last message sent by publish().
  129. if string(message) == "goodbye" {
  130. cancel()
  131. }
  132. return nil
  133. },
  134. "c1", "c2")
  135. if err != nil {
  136. fmt.Println(err)
  137. return
  138. }
  139. // Output:
  140. // channel: c1, message: hello
  141. // channel: c2, message: world
  142. // channel: c1, message: goodbye
  143. }