title: Ruby on Rails Bunny Gem for RabbitMQ
body: <p>I cannot figure out how to subscribe to my RabbitMQ locally(it worked when I used CloudAMPQ.) I suspect the problem is that my SendPriceJob isn't connected to the right connection/channel/exchange but I'm not certain.</p>
  
  <h3>I have a worker that fetches data from an API every one minute.</h3>
  
  <pre><code>class FetchPriceJob
    @queue = :update_price
  
    def self.perform
      # Do some stuff
  
      FetchPriceJob.new.publish(response.to_json)
    end
  
    def publish(data)
      channel.default_exchange.publish(data, routing_key: queue.name)
      connection.close
    end
  
    def connection
      @conn ||= begin
        conn = Bunny.new(host: "localhost", vhost: "/", user: "guest", password: "guest")
        conn.start
      end
    end
  
    def channel
      @channel ||= connection.create_channel
    end
  
    def queue
      @queue ||= channel.queue('current_prices')
    end
  end
  </code></pre>
  
  <h3>I have another worker that opens a connection and listens.</h3>
  
  <pre><code>module SendPriceJob
    @queue = :price_serve
  
    def self.perform
      conn = Bunny.new(host: "localhost", vhost: "/", user: "guest", password: "guest")
      conn.start
      ch  = conn.create_channel
      x   = ch.default_exchange
      q   = ch.queue('current_prices')
      begin
        q.subscribe(block: true) do |_, _, body|
          ActionCable.server.broadcast 'prices', body
        end
      rescue Interrupt =&gt; _
        ch.close
        conn.close
      end
    end
  end
  </code></pre>
  
  <h3>These two workers are kicked off by a process manager.</h3>
  
  <pre><code># Procfile
  elastic: elasticsearch
  redis: redis-server
  web: rails server -p 3000
  send_worker: QUEUE=price_serve rake resque:work
  fetch_worker: QUEUE=update_price rake resque:work
  scheduler: rake resque:scheduler
  </code></pre>
  
  <p>I'm running my RabbitMQ server: <a href="http://prntscr.com/i6rcwv" rel="nofollow noreferrer">http://prntscr.com/i6rcwv</a>. I'm successfully queueing messages on the connection/channel/exchange: <a href="http://prntscr.com/i6rd7q" rel="nofollow noreferrer">http://prntscr.com/i6rd7q</a>. From my logs it seems that the scheduler I'm running works, as does the producer: <a href="http://prntscr.com/i6rdxf" rel="nofollow noreferrer">http://prntscr.com/i6rdxf</a>.</p>
  
  <p>This is my first time working with <code>message queues</code> so I may have done something completely wrong. I feel like I should be close though because it was working with CloudAMQP. The only difference was that the <code>Bunny.new</code> was configured to connect to an external API.</p>