| 529 | } |
| 530 | |
| 531 | func ExamplePubSub() { |
| 532 | pubsub := rdb.Subscribe(ctx, "mychannel1") |
| 533 | |
| 534 | // Wait for confirmation that subscription is created before publishing anything. |
| 535 | _, err := pubsub.Receive(ctx) |
| 536 | if err != nil { |
| 537 | panic(err) |
| 538 | } |
| 539 | |
| 540 | // Go channel which receives messages. |
| 541 | ch := pubsub.Channel() |
| 542 | |
| 543 | // Publish a message. |
| 544 | err = rdb.Publish(ctx, "mychannel1", "hello").Err() |
| 545 | if err != nil { |
| 546 | panic(err) |
| 547 | } |
| 548 | |
| 549 | time.AfterFunc(time.Second, func() { |
| 550 | // When pubsub is closed channel is closed too. |
| 551 | _ = pubsub.Close() |
| 552 | }) |
| 553 | |
| 554 | // Consume messages. |
| 555 | for msg := range ch { |
| 556 | fmt.Println(msg.Channel, msg.Payload) |
| 557 | } |
| 558 | |
| 559 | // Output: mychannel1 hello |
| 560 | } |
| 561 | |
| 562 | func ExamplePubSub_Receive() { |
| 563 | pubsub := rdb.Subscribe(ctx, "mychannel2") |