プログラミング ミドルウェア

RabbitMQチュートリアル Part4

投稿日:

要約というか自分なりの解釈

routing_key を指定することで特定のメッセージを特定のコンシューマへメッセージを届けることができる。

パブリッシュする側

Publishする側はrouting_key指定してExchangeにdirectでパブリッシュする

  • tutrial_4_publish.rb
#!/usr/bin/env ruby
require 'bunny'

connection = Bunny.new
connection.start

channel = connection.create_channel
exchange = channel.direct('direct_exchange')

exchange.publish("test message", routing_key: "hogehoge")
exchange.publish("test message", routing_key: "fugafuga")

connection.close

コンシュームする側

コンシューマ側はExchangeとrouting_key指定してキューにバインドする

  • tutrial_4_consume.rb
#!/usr/bin/env ruby
require 'bunny'

connection = Bunny.new
connection.start

channel = connection.create_channel
exchange = channel.direct('direct_exchange')
queue = channel.queue('', exclusive: true)
queue.bind(exchange, routing_key: 'hogehoge')
queue.bind(exchange, routing_key: 'fugafuga')

begin
  queue.subscribe(block: true) do |delivery_info, _properties, body|
    puts " [x] #{delivery_info.routing_key}:#{body}"
  end
rescue Interrupt => _
  channel.close
  connection.close

  exit(0)
end

-プログラミング, ミドルウェア
-,

Copyright© 明日から頑張ります。 , 2025 All Rights Reserved Powered by STINGER.