Created
February 23, 2019 14:55
-
-
Save masnun/87ead6c8728681317d73461dfff9ae51 to your computer and use it in GitHub Desktop.
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 main | |
import ( | |
"encoding/json" | |
"log" | |
"os" | |
gopher_and_rabbit "github.com/masnun/gopher-and-rabbit" | |
"github.com/streadway/amqp" | |
) | |
func handleError(err error, msg string) { | |
if err != nil { | |
log.Fatalf("%s: %s", msg, err) | |
} | |
} | |
func main() { | |
conn, err := amqp.Dial(gopher_and_rabbit.Config.AMQPConnectionURL) | |
handleError(err, "Can't connect to AMQP") | |
defer conn.Close() | |
amqpChannel, err := conn.Channel() | |
handleError(err, "Can't create a amqpChannel") | |
defer amqpChannel.Close() | |
queue, err := amqpChannel.QueueDeclare("add", true, false, false, false, nil) | |
handleError(err, "Could not declare `add` queue") | |
err = amqpChannel.Qos(1, 0, false) | |
handleError(err, "Could not configure QoS") | |
messageChannel, err := amqpChannel.Consume( | |
queue.Name, | |
"", | |
false, | |
false, | |
false, | |
false, | |
nil, | |
) | |
handleError(err, "Could not register consumer") | |
stopChan := make(chan bool) | |
go func() { | |
log.Printf("Consumer ready, PID: %d", os.Getpid()) | |
for d := range messageChannel { | |
log.Printf("Received a message: %s", d.Body) | |
addTask := &gopher_and_rabbit.AddTask{} | |
err := json.Unmarshal(d.Body, addTask) | |
if err != nil { | |
log.Printf("Error decoding JSON: %s", err) | |
} | |
log.Printf("Result of %d + %d is : %d", addTask.Number1, addTask.Number2, addTask.Number1+addTask.Number2) | |
if err := d.Ack(false); err != nil { | |
log.Printf("Error acknowledging message : %s", err) | |
} else { | |
log.Printf("Acknowledged message") | |
} | |
} | |
}() | |
// Stop for program termination | |
<-stopChan | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment