github.com/vmware/transport-go@v1.3.4/plank/cmd/broker_sample/rabbitmq/producer.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/streadway/amqp" 8 "os" 9 ) 10 11 // GetNewConnection returns a new *amqp.Connection and error if any 12 func GetNewConnection(url string) (conn *amqp.Connection, err error) { 13 conn, err = amqp.Dial(url) 14 return 15 } 16 17 // GetNewChannel returns a new *amqp.Channel from the passed *amqp.Connection instance and error if any 18 func GetNewChannel(conn *amqp.Connection) (ch *amqp.Channel, err error) { 19 ch, err = conn.Channel() 20 return 21 } 22 23 // SendTopic sends a message to a topic exchange with routing key "something.somewhere". 24 // if environment variable LISTEN_METHOD is set to rbmq_stomp then the excahgne is set to 25 // amq.topic instead of logs_topic because RabbitMQ STOMP plugin routes incoming messages 26 // to the amq.topic exchange. 27 func SendTopic(ch *amqp.Channel) error { 28 var err error 29 listenMethod := os.Getenv("LISTEN_METHOD") 30 exchange := "logs_topic" 31 if listenMethod == "rbmq_stomp" { 32 // STOMP channels' queues are attached to amq.topic exchange 33 exchange = "amq.topic" 34 } 35 36 // publish a message to the exchange with routing key "something.somewhere" 37 if err = ch.Publish( 38 exchange, 39 "something.somewhere", 40 false, 41 false, 42 amqp.Publishing{ 43 ContentType: "text/plain", 44 Body: []byte("hello world"), 45 }); err != nil { 46 return err 47 } 48 return nil 49 } 50 51 // SendQueue sends a message to a direct exchange with routing key "testing". 52 func SendQueue(conn *amqp.Connection, ch *amqp.Channel) error { 53 var err error 54 // get a new channel from the connection 55 if ch, err = GetNewChannel(conn); err != nil { 56 return err 57 } 58 59 // publish a message to a direct exchange with routing key "testing" 60 if err = ch.Publish( 61 "", 62 "testing", 63 false, 64 false, 65 amqp.Publishing{ 66 ContentType: "text/plain", 67 Body: []byte("hello"), 68 }); err != nil { 69 return err 70 } 71 return nil 72 }