// NewPeer creates and returns a new Peer for communicating with AMQP brokers. func NewPeer(host string) (*Peer, error) { conn, err := amqp.Dial("amqp://*****:*****@" + host) if err != nil { return nil, err } channel, err := conn.Channel() if err != nil { return nil, err } queue, err := channel.QueueDeclare( broker.GenerateName(), // name false, // not durable false, // delete when unused true, // exclusive false, // no wait nil, // arguments ) if err != nil { return nil, err } err = channel.ExchangeDeclare( exchange, // name "fanout", // type false, // not durable false, // auto-deleted false, // internal false, // no wait nil, // arguments ) if err != nil { return nil, err } return &Peer{ conn: conn, queue: queue, channel: channel, send: make(chan []byte), errors: make(chan error, 1), done: make(chan bool), }, nil }
// Subscribe prepares the peer to consume messages. func (n *Peer) Subscribe() error { consumer, err := nsq.NewConsumer(topic, broker.GenerateName(), nsq.NewConfig()) if err != nil { return err } consumer.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error { n.messages <- message.Body return nil })) if err := consumer.ConnectToNSQD(n.host); err != nil { return err } n.consumer = consumer return nil }