Created
March 13, 2018 12:59
-
-
Save sohamkamani/fc2a647a9178077ade8fe5f464d3b654 to your computer and use it in GitHub Desktop.
An example of a simple pub-sub workflow for rabbitmq in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package queue | |
import ( | |
"fmt" | |
"log" | |
"github.com/streadway/amqp" | |
) | |
var conn *amqp.Connection | |
func Init(){ | |
var err error | |
conn, err = amqp.Dial("") | |
if err != nil { | |
log.Fatalf("could not connect to rabbitmq: %v", err) | |
panic(err) | |
} | |
} | |
func Publish(q string, msg []byte) error { | |
ch, err := conn.Channel() | |
if err != nil { | |
return err | |
} | |
defer ch.Close() | |
payload := amqp.Publishing{ | |
DeliveryMode: amqp.Persistent, | |
ContentType: "application/json", | |
Body: msg, | |
} | |
if err := ch.Publish("", q, false, false, payload); err != nil { | |
return fmt.Errorf("[Publish] failed to publish to queue %v", err) | |
} | |
return nil | |
} | |
func Subscribe(q string) (<-chan amqp.Delivery, error){ | |
ch, err := conn.Channel() | |
if err != nil { | |
return nil, err | |
} | |
defer ch.Close() | |
return ch.Consume(q, "", false, false, false, false, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment