Skip to content

Commit

Permalink
use PublishWithContext (#115)
Browse files Browse the repository at this point in the history
Signed-off-by: Gabriele Santomaggio <[email protected]>

Signed-off-by: Gabriele Santomaggio <[email protected]>
  • Loading branch information
Gsantomaggio authored Sep 6, 2022
1 parent ac70118 commit 20e949e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
6 changes: 5 additions & 1 deletion _examples/pubsub/pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"io"
"log"
"os"
"time"

amqp "github.com/rabbitmq/amqp091-go"
)
Expand Down Expand Up @@ -87,6 +88,9 @@ func redial(ctx context.Context, url string) chan chan session {
// publish publishes messages to a reconnecting session to a fanout exchange.
// It receives from the application specific source of messages.
func publish(sessions chan chan session, messages <-chan message) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

for session := range sessions {
var (
running bool
Expand Down Expand Up @@ -122,7 +126,7 @@ func publish(sessions chan chan session, messages <-chan message) {

case body = <-pending:
routingKey := "ignored for fanout exchanges, application dependent for other exchanges"
err := pub.Publish(exchange, routingKey, false, false, amqp.Publishing{
err := pub.PublishWithContext(ctx, exchange, routingKey, false, false, amqp.Publishing{
Body: body,
})
// Retry failed delivery on the next session
Expand Down
5 changes: 4 additions & 1 deletion _examples/simple-producer/producer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package main

import (
"context"
"flag"
"fmt"
"log"
Expand Down Expand Up @@ -101,12 +102,14 @@ func publish(done chan bool, amqpURI, exchange, exchangeType, routingKey, body s
}

Log.Println("declared Exchange, publishing messages")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

for {
seqNo := channel.GetNextPublishSeqNo()
Log.Printf("publishing %dB body (%q)", len(body), body)

if err := channel.Publish(
if err := channel.PublishWithContext(ctx,
exchange, // publish to an exchange
routingKey, // routing to 0 or more queues
false, // mandatory
Expand Down

0 comments on commit 20e949e

Please sign in to comment.