github.com/vmware/transport-go@v1.3.4/plank/cmd/broker_sample/rabbitmq/over_amqp.go (about)

     1  // Copyright 2019-2021 VMware, Inc.
     2  // SPDX-License-Identifier: BSD-2-Clause
     3  
     4  package rabbitmq
     5  
     6  import (
     7  	"github.com/vmware/transport-go/plank/utils"
     8  	"os"
     9  )
    10  
    11  // ListenViaAmqp directly connects to a RabbitMQ instance, sets up a sample topic exchange and
    12  // creates a queue that is bound with routing key "something.somewhere". this method is not using
    13  // any of Transport function but is useful to observe messages that originated from Transport.
    14  // for more details about RabbitMQ Golang examples refer to https://www.rabbitmq.com/getstarted.html
    15  func ListenViaAmqp(c2 chan os.Signal) {
    16  	// open a new RabbitMQ connection
    17  	conn, err := GetNewConnection("amqp://guest:guest@localhost:5672")
    18  	if err != nil {
    19  		utils.Log.Fatalln(err)
    20  	}
    21  
    22  	// acquire a new channel
    23  	ch, err := conn.Channel()
    24  	if err != nil {
    25  		utils.Log.Fatalln(err)
    26  	}
    27  	defer ch.Close()
    28  
    29  	// declare a new topic exchange
    30  	if err = ch.ExchangeDeclare(
    31  		"logs_topic",
    32  		"topic",
    33  		true,
    34  		false,
    35  		false,
    36  		false,
    37  		nil); err != nil {
    38  		utils.Log.Fatalln(err)
    39  	}
    40  
    41  	// declare a new queue
    42  	q, err := ch.QueueDeclare(
    43  		"",
    44  		false,
    45  		false,
    46  		true,
    47  		false,
    48  		nil)
    49  	if err != nil {
    50  		utils.Log.Fatalln(err)
    51  	}
    52  
    53  	// bind the queue with the exchange
    54  	if err = ch.QueueBind(
    55  		q.Name,
    56  		"something.somewhere",
    57  		"logs_topic",
    58  		false,
    59  		nil); err != nil {
    60  		utils.Log.Fatalln(err)
    61  	}
    62  
    63  	// consume the queue and acquire a channel for incoming messages
    64  	msgs, err := ch.Consume(
    65  		q.Name,
    66  		"",
    67  		true,
    68  		true,
    69  		false,
    70  		false,
    71  		nil)
    72  	if err != nil {
    73  		utils.Log.Fatalln(err)
    74  	}
    75  
    76  	// print out messages as soon as they arrive
    77  	go func() {
    78  		for m := range msgs {
    79  			utils.Log.Info(m)
    80  		}
    81  	}()
    82  
    83  	utils.Log.Infoln("waiting for messages")
    84  	<-c2
    85  }