Class: Bunny::Channel

Inherits:
Object
  • Object
show all
Defined in:
lib/bunny/channel.rb

Overview

Channels in RabbitMQ

To quote AMQP 0.9.1 specification:

AMQP 0.9.1 is a multi-channelled protocol. Channels provide a way to multiplex a heavyweight TCP/IP connection into several light weight connections. This makes the protocol more “firewall friendly” since port usage is predictable. It also means that traffic shaping and other network QoS features can be easily employed. Channels are independent of each other and can perform different functions simultaneously with other channels, the available bandwidth being shared between the concurrent activities.

Opening Channels

Channels can be opened either via Bunny::Session#create_channel (sufficient in the majority of cases) or by instantiating Bunny::Channel directly:

This will automatically allocate a channel id.

Closing Channels

Channels are closed via #close. Channels that get a channel-level exception are closed, too. Closed channels can no longer be used. Attempts to use them will raise ChannelAlreadyClosed.

Higher-level API

Bunny offers two sets of methods on Channel: known as higher-level and lower-level APIs, respectively. Higher-level API mimics amqp gem API where exchanges and queues are objects (instance of Exchange and Queue, respectively). Lower-level API is built around AMQP 0.9.1 methods (commands), where queues and exchanges are passed as strings (à la RabbitMQ Java client, Langohr and Pika).

Queue Operations In Higher-level API

  • #queue is used to declare queues. The rest of the API is in Queue.

Exchange Operations In Higher-level API

Channel Qos (Prefetch Level)

It is possible to control how many messages at most a consumer will be given (before it acknowledges or rejects previously consumed ones). This setting is per channel and controlled via #prefetch.

Channel IDs

Channels are identified by their ids which are integers. Bunny takes care of allocating and releasing them as channels are opened and closed. It is almost never necessary to specify channel ids explicitly.

There is a limit on the maximum number of channels per connection, usually 65536. Note that allocating channels is very cheap on both client and server so having tens, hundreds or even thousands of channels is not a problem.

Channels and Error Handling

Channel-level exceptions are more common than connection-level ones and often indicate issues applications can recover from (such as consuming from or trying to delete a queue that does not exist).

With Bunny, channel-level exceptions are raised as Ruby exceptions, for example, NotFound, that provide access to the underlying channel.close method information.

Examples:

conn = Bunny.new
conn.start

ch   = conn.create_channel

ch  = conn.create_channel
ch.close

Handling 404 NOT_FOUND

begin
  ch.queue_delete("queue_that_should_not_exist#{rand}")
rescue Bunny::NotFound => e
  puts "Channel-level exception! Code: #{e.channel_close.reply_code}, message: #{e.channel_close.reply_text}"
end

Handling 406 PRECONDITION_FAILED

begin
  ch2 = conn.create_channel
  q   = "bunny.examples.recovery.q#{rand}"

  ch2.queue_declare(q, :durable => false)
  ch2.queue_declare(q, :durable => true)
rescue Bunny::PreconditionFailed => e
  puts "Channel-level exception! Code: #{e.channel_close.reply_code}, message: #{e.channel_close.reply_text}"
ensure
  conn.create_channel.queue_delete(q)
end

See Also:

Constant Summary

DEFAULT_CONTENT_TYPE =
"application/octet-stream".freeze

Instance Attribute Summary collapse

Backwards compatibility with 0.8.0 collapse

Higher-level API for exchange operations collapse

Higher-level API for queue operations collapse

QoS and Flow Control collapse

Message acknowledgements collapse

Consumer and Message operations (basic.*) collapse

Queue operations (queue.*) collapse

Exchange operations (exchange.*) collapse

Flow control (channel.*) collapse

Transactions (tx.*) collapse

Publisher Confirms (confirm.*) collapse

Misc collapse

Network Failure Recovery collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection = nil, id = nil, work_pool = ConsumerWorkPool.new(1)) ⇒ Channel



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/bunny/channel.rb', line 165

def initialize(connection = nil, id = nil, work_pool = ConsumerWorkPool.new(1))
  @connection = connection
  @logger     = connection.logger
  @id         = id || @connection.next_channel_id
  @status     = :opening

  @connection.register_channel(self)

  @queues     = Hash.new
  @exchanges  = Hash.new
  @consumers  = Hash.new
  @work_pool  = work_pool

  # synchronizes frameset delivery. MK.
  @publishing_mutex = @connection.mutex_impl.new
  @consumer_mutex   = @connection.mutex_impl.new

  @unconfirmed_set_mutex = @connection.mutex_impl.new

  self.reset_continuations

  # threads awaiting on continuations. Used to unblock
  # them when network connection goes down so that busy loops
  # that perform synchronous operations can work. MK.
  @threads_waiting_on_continuations           = Set.new
  @threads_waiting_on_confirms_continuations  = Set.new
  @threads_waiting_on_basic_get_continuations = Set.new

  @next_publish_seq_no = 0

  @recoveries_counter = Bunny::Concurrent::AtomicFixnum.new(0)
  @uncaught_exception_handler = Proc.new do |e, consumer|
    @logger.error "Uncaught exception from consumer #{consumer.to_s}: #{e.message}"
  end
end

Instance Attribute Details

#connectionBunny::Session (readonly)



142
143
144
# File 'lib/bunny/channel.rb', line 142

def connection
  @connection
end

#consumersHash<String, Bunny::Consumer> (readonly)



158
159
160
# File 'lib/bunny/channel.rb', line 158

def consumers
  @consumers
end

#exchangesHash<String, Bunny::Exchange> (readonly)



152
153
154
# File 'lib/bunny/channel.rb', line 152

def exchanges
  @exchanges
end

#idInteger



140
141
142
# File 'lib/bunny/channel.rb', line 140

def id
  @id
end

#nacked_setSet<Integer> (readonly)



156
157
158
# File 'lib/bunny/channel.rb', line 156

def nacked_set
  @nacked_set
end

#next_publish_seq_noInteger (readonly)



148
149
150
# File 'lib/bunny/channel.rb', line 148

def next_publish_seq_no
  @next_publish_seq_no
end

#queuesHash<String, Bunny::Queue> (readonly)



150
151
152
# File 'lib/bunny/channel.rb', line 150

def queues
  @queues
end

#recoveries_counterObject (readonly)

Returns the value of attribute recoveries_counter



201
202
203
# File 'lib/bunny/channel.rb', line 201

def recoveries_counter
  @recoveries_counter
end

#statusSymbol (readonly)



144
145
146
# File 'lib/bunny/channel.rb', line 144

def status
  @status
end

#unconfirmed_setSet<Integer> (readonly)



154
155
156
# File 'lib/bunny/channel.rb', line 154

def unconfirmed_set
  @unconfirmed_set
end

#work_poolBunny::ConsumerWorkPool (readonly)



146
147
148
# File 'lib/bunny/channel.rb', line 146

def work_pool
  @work_pool
end

Instance Method Details

#ack(delivery_tag, multiple = false) ⇒ Object Also known as: acknowledge

Acknowledges a message. Acknowledged messages are completely removed from the queue.



462
463
464
465
466
# File 'lib/bunny/channel.rb', line 462

def ack(delivery_tag, multiple = false)
  guarding_against_stale_delivery_tags(delivery_tag) do
    basic_ack(delivery_tag.to_i, multiple)
  end
end

#activeBoolean



257
258
259
# File 'lib/bunny/channel.rb', line 257

def active
  open?
end

#any_consumers?Boolean

Returns true if there are consumers on this channel



928
929
930
# File 'lib/bunny/channel.rb', line 928

def any_consumers?
  @consumer_mutex.synchronize { @consumers.any? }
end

#basic_ack(delivery_tag, multiple) ⇒ NilClass

Acknowledges a delivery (message).

Examples:

Ack a message

conn  = Bunny.new
conn.start

ch    = conn.create_channel
q.subscribe do |delivery_info, properties, payload|
  # requeue the message
  ch.basic_ack(delivery_info.delivery_tag)
end

Ack a message fetched via basic.get

conn  = Bunny.new
conn.start

ch    = conn.create_channel
# we assume the queue exists and has messages
delivery_info, properties, payload = ch.basic_get("bunny.examples.queue3", :ack => true)
ch.basic_ack(delivery_info.delivery_tag)

Ack multiple messages fetched via basic.get

conn  = Bunny.new
conn.start

ch    = conn.create_channel
# we assume the queue exists and has messages
_, _, payload1 = ch.basic_get("bunny.examples.queue3", :ack => true)
_, _, payload2 = ch.basic_get("bunny.examples.queue3", :ack => true)
delivery_info, properties, payload3 = ch.basic_get("bunny.examples.queue3", :ack => true)
# ack all fetched messages up to payload3
ch.basic_ack(delivery_info.delivery_tag, true)

See Also:



723
724
725
726
727
728
# File 'lib/bunny/channel.rb', line 723

def basic_ack(delivery_tag, multiple)
  raise_if_no_longer_open!
  @connection.send_frame(AMQ::Protocol::Basic::Ack.encode(@id, delivery_tag, multiple))

  nil
end

#basic_cancel(consumer_tag) ⇒ AMQ::Protocol::Basic::CancelOk

Removes a consumer. Messages for this consumer will no longer be delivered. If the queue it was on is auto-deleted and this consumer was the last one, the queue will be deleted.



914
915
916
917
918
919
920
921
922
923
924
# File 'lib/bunny/channel.rb', line 914

def basic_cancel(consumer_tag)
  @connection.send_frame(AMQ::Protocol::Basic::Cancel.encode(@id, consumer_tag, false))

  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_basic_cancel_ok = wait_on_continuations
  end

  maybe_kill_consumer_work_pool! unless any_consumers?

  @last_basic_cancel_ok
end

#basic_consume(queue, consumer_tag = generate_consumer_tag, no_ack = false, exclusive = false, arguments = nil, &block) ⇒ AMQ::Protocol::Basic::ConsumeOk Also known as: consume

Registers a consumer for queue. Delivered messages will be handled with the block provided to this method.



806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/bunny/channel.rb', line 806

def basic_consume(queue, consumer_tag = generate_consumer_tag, no_ack = false, exclusive = false, arguments = nil, &block)
  raise_if_no_longer_open!
  maybe_start_consumer_work_pool!

  queue_name = if queue.respond_to?(:name)
                 queue.name
               else
                 queue
               end

  # helps avoid race condition between basic.consume-ok and basic.deliver if there are messages
  # in the queue already. MK.
  if consumer_tag && consumer_tag.strip != AMQ::Protocol::EMPTY_STRING
    add_consumer(queue_name, consumer_tag, no_ack, exclusive, arguments, &block)
  end

  @connection.send_frame(AMQ::Protocol::Basic::Consume.encode(@id,
      queue_name,
      consumer_tag,
      false,
      no_ack,
      exclusive,
      false,
      arguments))

  begin
    Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
      @last_basic_consume_ok = wait_on_continuations
    end
  rescue Exception => e
    # if basic.consume-ok never arrives, unregister the proactively
    # registered consumer. MK.
    unregister_consumer(@last_basic_consume_ok.consumer_tag)

    raise e
  end

  # in case there is another exclusive consumer and we get a channel.close
  # response here. MK.
  raise_if_channel_close!(@last_basic_consume_ok)

  # covers server-generated consumer tags
  add_consumer(queue_name, @last_basic_consume_ok.consumer_tag, no_ack, exclusive, arguments, &block)

  @last_basic_consume_ok
end

#basic_consume_with(consumer) ⇒ AMQ::Protocol::Basic::ConsumeOk Also known as: consume_with

Registers a consumer for queue as Bunny::Consumer instance.



862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# File 'lib/bunny/channel.rb', line 862

def basic_consume_with(consumer)
  raise_if_no_longer_open!
  maybe_start_consumer_work_pool!

  # helps avoid race condition between basic.consume-ok and basic.deliver if there are messages
  # in the queue already. MK.
  if consumer.consumer_tag && consumer.consumer_tag.strip != AMQ::Protocol::EMPTY_STRING
    register_consumer(consumer.consumer_tag, consumer)
  end

  @connection.send_frame(AMQ::Protocol::Basic::Consume.encode(@id,
      consumer.queue_name,
      consumer.consumer_tag,
      false,
      consumer.no_ack,
      consumer.exclusive,
      false,
      consumer.arguments))

  begin
    Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
      @last_basic_consume_ok = wait_on_continuations
    end
  rescue Exception => e
    # if basic.consume-ok never arrives, unregister the proactively
    # registered consumer. MK.
    unregister_consumer(@last_basic_consume_ok.consumer_tag)

    raise e
  end

  # in case there is another exclusive consumer and we get a channel.close
  # response here. MK.
  raise_if_channel_close!(@last_basic_consume_ok)

  # covers server-generated consumer tags
  register_consumer(@last_basic_consume_ok.consumer_tag, consumer)

  raise_if_continuation_resulted_in_a_channel_error!

  @last_basic_consume_ok
end

#basic_get(queue, opts = {:ack => true}) ⇒ Array

Synchronously fetches a message from the queue, if there are any. This method is for cases when the convenience of synchronous operations is more important than throughput.

Examples:

Using Bunny::Channel#basic_get with manual acknowledgements

conn = Bunny.new
conn.start
ch   = conn.create_channel
# here we assume the queue already exists and has messages
delivery_info, properties, payload = ch.basic_get("bunny.examples.queue1", :ack => true)
ch.acknowledge(delivery_info.delivery_tag)

Options Hash (opts):

  • :ack (Boolean) — default: true

    Will this message be acknowledged manually?

See Also:



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'lib/bunny/channel.rb', line 575

def basic_get(queue, opts = {:ack => true})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Basic::Get.encode(@id, queue, !(opts[:ack])))
  # this is a workaround for the edge case when basic_get is called in a tight loop
  # and network goes down we need to perform recovery. The problem is, basic_get will
  # keep blocking the thread that calls it without clear way to constantly unblock it
  # from the network activity loop (where recovery happens) with the current continuations
  # implementation (and even more correct and convenient ones, such as wait/notify, should
  # we implement them). So we return a triple of nils immediately which apps should be
  # able to handle anyway as "got no message, no need to act". MK.
  @last_basic_get_response = if @connection.open?
                               wait_on_basic_get_continuations
                             else
                               [nil, nil, nil]
                             end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_basic_get_response
end

#basic_nack(delivery_tag, multiple = false, requeue = false) ⇒ NilClass

Rejects or requeues messages just like #basic_reject but can do so with multiple messages at once.

Examples:

Requeue a message

conn  = Bunny.new
conn.start

ch    = conn.create_channel
q.subscribe do |delivery_info, properties, payload|
  # requeue the message
  ch.basic_nack(delivery_info.delivery_tag, false, true)
end

Reject a message

conn  = Bunny.new
conn.start

ch    = conn.create_channel
q.subscribe do |delivery_info, properties, payload|
  # requeue the message
  ch.basic_nack(delivery_info.delivery_tag)
end

Requeue a message fetched via basic.get

conn  = Bunny.new
conn.start

ch    = conn.create_channel
# we assume the queue exists and has messages
delivery_info, properties, payload = ch.basic_get("bunny.examples.queue3", :ack => true)
ch.basic_nack(delivery_info.delivery_tag, false, true)

Requeue multiple messages fetched via basic.get

conn  = Bunny.new
conn.start

ch    = conn.create_channel
# we assume the queue exists and has messages
_, _, payload1 = ch.basic_get("bunny.examples.queue3", :ack => true)
_, _, payload2 = ch.basic_get("bunny.examples.queue3", :ack => true)
delivery_info, properties, payload3 = ch.basic_get("bunny.examples.queue3", :ack => true)
# requeue all fetched messages up to payload3
ch.basic_nack(delivery_info.delivery_tag, true, true)

See Also:



783
784
785
786
787
788
789
790
791
# File 'lib/bunny/channel.rb', line 783

def basic_nack(delivery_tag, multiple = false, requeue = false)
  raise_if_no_longer_open!
  @connection.send_frame(AMQ::Protocol::Basic::Nack.encode(@id,
      delivery_tag,
      multiple,
      requeue))

  nil
end

#basic_publish(payload, exchange, routing_key, opts = {}) ⇒ Bunny::Channel

Publishes a message using basic.publish AMQP 0.9.1 method.

Options Hash (opts):

  • :persistent (Boolean)

    Should the message be persisted to disk?

  • :mandatory (Boolean)

    Should the message be returned if it cannot be routed to any queue?

  • :timestamp (Integer)

    A timestamp associated with this message

  • :expiration (Integer)

    Expiration time after which the message will be deleted

  • :type (String)

    Message type, e.g. what type of event or command this message represents. Can be any string

  • :reply_to (String)

    Queue name other apps should send the response to

  • :content_type (String)

    Message content type (e.g. application/json)

  • :content_encoding (String)

    Message content encoding (e.g. gzip)

  • :correlation_id (String)

    Message correlated to this one, e.g. what request this message is a reply for

  • :priority (Integer)

    Message priority, 0 to 9. Not used by RabbitMQ, only applications

  • :message_id (String)

    Any message identifier

  • :user_id (String)

    Optional user ID. Verified by RabbitMQ against the actual connection username

  • :app_id (String)

    Optional application ID



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/bunny/channel.rb', line 517

def basic_publish(payload, exchange, routing_key, opts = {})
  raise_if_no_longer_open!

  exchange_name = if exchange.respond_to?(:name)
                    exchange.name
                  else
                    exchange
                  end

  mode = if opts.fetch(:persistent, true)
           2
         else
           1
         end

  opts[:delivery_mode] ||= mode
  opts[:content_type]  ||= DEFAULT_CONTENT_TYPE
  opts[:priority]      ||= 0

  if @next_publish_seq_no > 0
    @unconfirmed_set.add(@next_publish_seq_no)
    @next_publish_seq_no += 1
  end

  frames = AMQ::Protocol::Basic::Publish.encode(@id,
    payload,
    opts,
    exchange_name,
    routing_key,
    opts[:mandatory],
    false,
    @connection.frame_max)
  @connection.send_frameset_without_timeout(frames, self)

  self
end

#basic_qos(prefetch_count, global = false) ⇒ AMQ::Protocol::Basic::QosOk

Controls message delivery rate using basic.qos AMQP 0.9.1 method.

Raises:

  • (ArgumentError)

See Also:



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/bunny/channel.rb', line 605

def basic_qos(prefetch_count, global = false)
  raise ArgumentError.new("prefetch count must be a positive integer, given: #{prefetch_count}") if prefetch_count < 0
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Basic::Qos.encode(@id, 0, prefetch_count, global))

  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_basic_qos_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @prefetch_count = prefetch_count

  @last_basic_qos_ok
end

#basic_recover(requeue) ⇒ AMQ::Protocol::Basic::RecoverOk

Redeliver unacknowledged messages



626
627
628
629
630
631
632
633
634
635
636
# File 'lib/bunny/channel.rb', line 626

def basic_recover(requeue)
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Basic::Recover.encode(@id, requeue))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_basic_recover_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_basic_recover_ok
end

#basic_reject(delivery_tag, requeue) ⇒ NilClass

Rejects or requeues a message.

Examples:

Requeue a message

conn  = Bunny.new
conn.start

ch    = conn.create_channel
q.subscribe do |delivery_info, properties, payload|
  # requeue the message
  ch.basic_reject(delivery_info.delivery_tag, true)
end

Reject a message

conn  = Bunny.new
conn.start

ch    = conn.create_channel
q.subscribe do |delivery_info, properties, payload|
  # requeue the message
  ch.basic_reject(delivery_info.delivery_tag, false)
end

Requeue a message fetched via basic.get

conn  = Bunny.new
conn.start

ch    = conn.create_channel
# we assume the queue exists and has messages
delivery_info, properties, payload = ch.basic_get("bunny.examples.queue3", :ack => true)
ch.basic_reject(delivery_info.delivery_tag, true)

See Also:



676
677
678
679
680
681
# File 'lib/bunny/channel.rb', line 676

def basic_reject(delivery_tag, requeue)
  raise_if_no_longer_open!
  @connection.send_frame(AMQ::Protocol::Basic::Reject.encode(@id, delivery_tag, requeue))

  nil
end

#channel_flow(active) ⇒ AMQ::Protocol::Channel::FlowOk

Note:

Recent (e.g. 2.8.x., 3.x) RabbitMQ will employ TCP/IP-level back pressure on publishers if it detects that consumers do not keep up with them.

Enables or disables message flow for the channel. When message flow is disabled, no new messages will be delivered to consumers on this channel. This is typically used by consumers that cannot keep up with the influx of messages.



1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
# File 'lib/bunny/channel.rb', line 1258

def channel_flow(active)
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Channel::Flow.encode(@id, active))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_channel_flow_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_channel_flow_ok
end

#clientBunny::Session



262
263
264
# File 'lib/bunny/channel.rb', line 262

def client
  @connection
end

#closeObject

Closes the channel. Closed channels can no longer be used (this includes associated Queue, Exchange and Bunny::Consumer instances.



228
229
230
231
232
# File 'lib/bunny/channel.rb', line 228

def close
  @connection.close_channel(self)
  closed!
  maybe_kill_consumer_work_pool!
end

#closed?Boolean

Returns true if this channel is closed (manually or because of an exception), false otherwise



242
243
244
# File 'lib/bunny/channel.rb', line 242

def closed?
  @status == :closed
end

#confirm_select(callback = nil) ⇒ AMQ::Protocol::Confirm::SelectOk

Enables publisher confirms for the channel.



1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
# File 'lib/bunny/channel.rb', line 1341

def confirm_select(callback=nil)
  raise_if_no_longer_open!

  if @next_publish_seq_no == 0
    @confirms_continuations = new_continuation
    @unconfirmed_set        = Set.new
    @nacked_set             = Set.new
    @next_publish_seq_no    = 1
  end

  @confirms_callback = callback

  @connection.send_frame(AMQ::Protocol::Confirm::Select.encode(@id, false))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_confirm_select_ok = wait_on_continuations
  end
  @confirm_mode = true
  raise_if_continuation_resulted_in_a_channel_error!
  @last_confirm_select_ok
end

#default_exchangeObject

Provides access to the default exchange



355
356
357
# File 'lib/bunny/channel.rb', line 355

def default_exchange
  self.direct(AMQ::Protocol::EMPTY_STRING, :no_declare => true)
end

#direct(name, opts = {}) ⇒ Bunny::Exchange

Declares a direct exchange or looks it up in the cache of previously declared exchanges.

Options Hash (opts):

  • :durable (Boolean) — default: false

    Should the exchange be durable?

  • :auto_delete (Boolean) — default: false

    Should the exchange be automatically deleted when no longer in use?

  • :arguments (Hash) — default: {}

    Optional exchange arguments (used by RabbitMQ extensions)

See Also:



312
313
314
# File 'lib/bunny/channel.rb', line 312

def direct(name, opts = {})
  Exchange.new(self, :direct, name, opts)
end

#exchange(name, opts = {}) ⇒ Bunny::Exchange

Declares a headers exchange or looks it up in the cache of previously declared exchanges.

Options Hash (opts):

  • :type (String, Symbol) — default: :direct

    Exchange type, e.g. :fanout or "x-consistent-hash"

  • :durable (Boolean) — default: false

    Should the exchange be durable?

  • :auto_delete (Boolean) — default: false

    Should the exchange be automatically deleted when no longer in use?

  • :arguments (Hash) — default: {}

    Optional exchange arguments

See Also:



373
374
375
# File 'lib/bunny/channel.rb', line 373

def exchange(name, opts = {})
  Exchange.new(self, opts.fetch(:type, :direct), name, opts)
end

#exchange_bind(source, destination, opts = {}) ⇒ AMQ::Protocol::Exchange::BindOk

Binds an exchange to another exchange using exchange.bind AMQP 0.9.1 extension that RabbitMQ provides.

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

See Also:



1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
# File 'lib/bunny/channel.rb', line 1169

def exchange_bind(source, destination, opts = {})
  raise_if_no_longer_open!

  source_name = if source.respond_to?(:name)
                  source.name
                else
                  source
                end

  destination_name = if destination.respond_to?(:name)
                       destination.name
                     else
                       destination
                     end

  @connection.send_frame(AMQ::Protocol::Exchange::Bind.encode(@id,
      destination_name,
      source_name,
      opts[:routing_key],
      false,
      opts[:arguments]))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_exchange_bind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_exchange_bind_ok
end

#exchange_declare(name, type, opts = {}) ⇒ AMQ::Protocol::Exchange::DeclareOk

Declares a echange using echange.declare AMQP 0.9.1 method.

Options Hash (opts):

  • durable (Boolean) — default: false

    Should information about this echange be persisted to disk so that it can survive broker restarts? Typically set to true for long-lived exchanges.

  • auto_delete (Boolean) — default: false

    Should this echange be deleted when it is no longer used?

  • passive (Boolean) — default: false

    If true, exchange will be checked for existence. If it does not exist, NotFound will be raised.

See Also:



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
# File 'lib/bunny/channel.rb', line 1109

def exchange_declare(name, type, opts = {})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Exchange::Declare.encode(@id,
      name,
      type.to_s,
      opts.fetch(:passive, false),
      opts.fetch(:durable, false),
      opts.fetch(:auto_delete, false),
      opts.fetch(:internal, false),
      false, # nowait
      opts[:arguments]))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_exchange_declare_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_exchange_declare_ok
end

#exchange_delete(name, opts = {}) ⇒ AMQ::Protocol::Exchange::DeleteOk

Deletes a exchange using exchange.delete AMQP 0.9.1 method

Options Hash (opts):

  • if_unused (Boolean) — default: false

    Should this exchange be deleted only if it is no longer used

See Also:



1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
# File 'lib/bunny/channel.rb', line 1139

def exchange_delete(name, opts = {})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Exchange::Delete.encode(@id,
      name,
      opts[:if_unused],
      false))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_exchange_delete_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_exchange_delete_ok
end

#exchange_unbind(source, destination, opts = {}) ⇒ AMQ::Protocol::Exchange::UnbindOk

Unbinds an exchange from another exchange using exchange.unbind AMQP 0.9.1 extension that RabbitMQ provides.

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

See Also:



1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
# File 'lib/bunny/channel.rb', line 1213

def exchange_unbind(source, destination, opts = {})
  raise_if_no_longer_open!

  source_name = if source.respond_to?(:name)
                  source.name
                else
                  source
                end

  destination_name = if destination.respond_to?(:name)
                       destination.name
                     else
                       destination
                     end

  @connection.send_frame(AMQ::Protocol::Exchange::Unbind.encode(@id,
      destination_name,
      source_name,
      opts[:routing_key],
      false,
      opts[:arguments]))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_exchange_unbind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_exchange_unbind_ok
end

#fanout(name, opts = {}) ⇒ Bunny::Exchange

Declares a fanout exchange or looks it up in the cache of previously declared exchanges.

Options Hash (opts):

  • :durable (Boolean) — default: false

    Should the exchange be durable?

  • :auto_delete (Boolean) — default: false

    Should the exchange be automatically deleted when no longer in use?

  • :arguments (Hash) — default: {}

    Optional exchange arguments (used by RabbitMQ extensions)

See Also:



294
295
296
# File 'lib/bunny/channel.rb', line 294

def fanout(name, opts = {})
  Exchange.new(self, :fanout, name, opts)
end

#flow(active) ⇒ Object

Flow control. When set to false, RabbitMQ will stop delivering messages on this channel.



423
424
425
# File 'lib/bunny/channel.rb', line 423

def flow(active)
  channel_flow(active)
end

#generate_consumer_tag(name = "bunny") ⇒ String

Unique string supposed to be used as a consumer tag.



1393
1394
1395
# File 'lib/bunny/channel.rb', line 1393

def generate_consumer_tag(name = "bunny")
  "#{name}-#{Time.now.to_i * 1000}-#{Kernel.rand(999_999_999_999)}"
end

#headers(name, opts = {}) ⇒ Bunny::Exchange

Declares a headers exchange or looks it up in the cache of previously declared exchanges.

Options Hash (opts):

  • :durable (Boolean) — default: false

    Should the exchange be durable?

  • :auto_delete (Boolean) — default: false

    Should the exchange be automatically deleted when no longer in use?

  • :arguments (Hash) — default: {}

    Optional exchange arguments

See Also:



348
349
350
# File 'lib/bunny/channel.rb', line 348

def headers(name, opts = {})
  Exchange.new(self, :headers, name, opts)
end

#nack(delivery_tag, multiple = false, requeue = false) ⇒ Object

Rejects a message. A rejected message can be requeued or dropped by RabbitMQ. This method is similar to #reject but supports rejecting multiple messages at once, and is usually preferred.



479
480
481
482
483
# File 'lib/bunny/channel.rb', line 479

def nack(delivery_tag, multiple = false, requeue = false)
  guarding_against_stale_delivery_tags(delivery_tag) do
    basic_nack(delivery_tag.to_i, multiple, requeue)
  end
end

#numberInteger



252
253
254
# File 'lib/bunny/channel.rb', line 252

def number
  self.id
end

#on_error(&block) ⇒ Object

Defines a handler for errors that are not responses to a particular operations (e.g. basic.ack, basic.reject, basic.nack).



1408
1409
1410
# File 'lib/bunny/channel.rb', line 1408

def on_error(&block)
  @on_error = block
end

#on_uncaught_exception(&block) ⇒ Object

Defines a handler for uncaught exceptions in consumers (e.g. delivered message handlers).



1416
1417
1418
# File 'lib/bunny/channel.rb', line 1416

def on_uncaught_exception(&block)
  @uncaught_exception_handler = block
end

#openBunny::Channel

Opens the channel and resets its internal state



211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/bunny/channel.rb', line 211

def open
  @threads_waiting_on_continuations           = Set.new
  @threads_waiting_on_confirms_continuations  = Set.new
  @threads_waiting_on_basic_get_continuations = Set.new

  @connection.open_channel(self)
  # clear last channel error
  @last_channel_error = nil

  @status = :open

  self
end

#open?Boolean

Returns true if this channel is open, false otherwise



236
237
238
# File 'lib/bunny/channel.rb', line 236

def open?
  @status == :open
end

#prefetch(prefetch_count) ⇒ Object

Sets how many messages will be given to consumers on this channel before they have to acknowledge or reject one of the previously consumed messages



414
415
416
# File 'lib/bunny/channel.rb', line 414

def prefetch(prefetch_count)
  self.basic_qos(prefetch_count, false)
end

#queue(name = AMQ::Protocol::EMPTY_STRING, opts = {}) ⇒ Bunny::Queue

Declares a queue or looks it up in the per-channel cache.

Options Hash (opts):

  • :durable (Boolean) — default: false

    Should this queue be durable?

  • :auto-delete (Boolean) — default: false

    Should this queue be automatically deleted when the last consumer disconnects?

  • :exclusive (Boolean) — default: false

    Should this queue be exclusive (only can be used by this connection, removed when the connection is closed)?

  • :arguments (Boolean) — default: {}

    Additional optional arguments (typically used by RabbitMQ extensions and plugins)

See Also:



396
397
398
399
400
# File 'lib/bunny/channel.rb', line 396

def queue(name = AMQ::Protocol::EMPTY_STRING, opts = {})
  q = find_queue(name) || Bunny::Queue.new(self, name, opts)

  register_queue(q)
end

#queue_bind(name, exchange, opts = {}) ⇒ AMQ::Protocol::Queue::BindOk

Binds a queue to an exchange using queue.bind AMQP 0.9.1 method

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

See Also:



1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
# File 'lib/bunny/channel.rb', line 1032

def queue_bind(name, exchange, opts = {})
  raise_if_no_longer_open!

  exchange_name = if exchange.respond_to?(:name)
                    exchange.name
                  else
                    exchange
                  end

  @connection.send_frame(AMQ::Protocol::Queue::Bind.encode(@id,
      name,
      exchange_name,
      opts[:routing_key],
      false,
      opts[:arguments]))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_queue_bind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_queue_bind_ok
end

#queue_declare(name, opts = {}) ⇒ AMQ::Protocol::Queue::DeclareOk

Declares a queue using queue.declare AMQP 0.9.1 method.

Options Hash (opts):

  • durable (Boolean) — default: false

    Should information about this queue be persisted to disk so that it can survive broker restarts? Typically set to true for long-lived queues.

  • auto_delete (Boolean) — default: false

    Should this queue be deleted when the last consumer is cancelled?

  • exclusive (Boolean) — default: false

    Should only this connection be able to use this queue? If true, the queue will be automatically deleted when this connection is closed

  • passive (Boolean) — default: false

    If true, queue will be checked for existence. If it does not exist, NotFound will be raised.

See Also:



954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/bunny/channel.rb', line 954

def queue_declare(name, opts = {})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Queue::Declare.encode(@id,
      name,
      opts.fetch(:passive, false),
      opts.fetch(:durable, false),
      opts.fetch(:exclusive, false),
      opts.fetch(:auto_delete, false),
      false,
      opts[:arguments]))
  @last_queue_declare_ok = wait_on_continuations

  raise_if_continuation_resulted_in_a_channel_error!

  @last_queue_declare_ok
end

#queue_delete(name, opts = {}) ⇒ AMQ::Protocol::Queue::DeleteOk

Deletes a queue using queue.delete AMQP 0.9.1 method

Options Hash (opts):

  • if_unused (Boolean) — default: false

    Should this queue be deleted only if it has no consumers?

  • if_empty (Boolean) — default: false

    Should this queue be deleted only if it has no messages?

See Also:



983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
# File 'lib/bunny/channel.rb', line 983

def queue_delete(name, opts = {})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Queue::Delete.encode(@id,
      name,
      opts[:if_unused],
      opts[:if_empty],
      false))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_queue_delete_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_queue_delete_ok
end

#queue_purge(name, opts = {}) ⇒ AMQ::Protocol::Queue::PurgeOk

Purges a queue (removes all messages from it) using queue.purge AMQP 0.9.1 method.



1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
# File 'lib/bunny/channel.rb', line 1006

def queue_purge(name, opts = {})
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Queue::Purge.encode(@id, name, false))

  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_queue_purge_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_queue_purge_ok
end

#queue_unbind(name, exchange, opts = {}) ⇒ AMQ::Protocol::Queue::UnbindOk

Unbinds a queue from an exchange using queue.unbind AMQP 0.9.1 method

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

See Also:



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/bunny/channel.rb', line 1068

def queue_unbind(name, exchange, opts = {})
  raise_if_no_longer_open!

  exchange_name = if exchange.respond_to?(:name)
                    exchange.name
                  else
                    exchange
                  end

  @connection.send_frame(AMQ::Protocol::Queue::Unbind.encode(@id,
      name,
      exchange_name,
      opts[:routing_key],
      opts[:arguments]))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_queue_unbind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  @last_queue_unbind_ok
end

#recover(ignored = true) ⇒ Object

Tells RabbitMQ to redeliver unacknowledged messages



429
430
431
432
# File 'lib/bunny/channel.rb', line 429

def recover(ignored = true)
  # RabbitMQ only supports basic.recover with requeue = true
  basic_recover(true)
end

#recover_confirm_modeObject

Recovers publisher confirms mode. Used by the Automatic Network Failure Recovery feature.



1456
1457
1458
# File 'lib/bunny/channel.rb', line 1456

def recover_confirm_mode
  confirm_select if @confirm_mode
end

#recover_consumersObject

Recovers consumers. Used by the Automatic Network Failure Recovery feature.



1493
1494
1495
1496
1497
1498
1499
1500
1501
# File 'lib/bunny/channel.rb', line 1493

def recover_consumers
  unless @consumers.empty?
    @work_pool = ConsumerWorkPool.new(@work_pool.size)
    @work_pool.start
  end
  @consumers.values.dup.each do |c|
    c.recover_from_network_failure
  end
end

#recover_exchangesObject

Recovers exchanges. Used by the Automatic Network Failure Recovery feature.



1472
1473
1474
1475
1476
# File 'lib/bunny/channel.rb', line 1472

def recover_exchanges
  @exchanges.values.dup.each do |x|
    x.recover_from_network_failure
  end
end

#recover_from_network_failureObject

Recovers basic.qos setting, exchanges, queues and consumers. Used by the Automatic Network Failure Recovery feature.



1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
# File 'lib/bunny/channel.rb', line 1430

def recover_from_network_failure
  @logger.debug "Recovering channel #{@id} after network failure"
  release_all_continuations

  recover_prefetch_setting
  recover_confirm_mode
  recover_tx_mode
  recover_exchanges
  # this includes recovering bindings
  recover_queues
  recover_consumers
  increment_recoveries_counter
end

#recover_prefetch_settingObject

Recovers basic.qos setting. Used by the Automatic Network Failure Recovery feature.



1448
1449
1450
# File 'lib/bunny/channel.rb', line 1448

def recover_prefetch_setting
  basic_qos(@prefetch_count) if @prefetch_count
end

#recover_queuesObject

Recovers queues and bindings. Used by the Automatic Network Failure Recovery feature.



1482
1483
1484
1485
1486
1487
# File 'lib/bunny/channel.rb', line 1482

def recover_queues
  @queues.values.dup.each do |q|
    @logger.debug "Recovering queue #{q.name}"
    q.recover_from_network_failure
  end
end

#recover_tx_modeObject

Recovers transaction mode. Used by the Automatic Network Failure Recovery feature.



1464
1465
1466
# File 'lib/bunny/channel.rb', line 1464

def recover_tx_mode
  tx_select if @tx_mode
end

#reject(delivery_tag, requeue = false) ⇒ Object

Rejects a message. A rejected message can be requeued or dropped by RabbitMQ.



449
450
451
452
453
# File 'lib/bunny/channel.rb', line 449

def reject(delivery_tag, requeue = false)
  guarding_against_stale_delivery_tags(delivery_tag) do
    basic_reject(delivery_tag.to_i, requeue)
  end
end

#synchronize(&block) ⇒ Object

Synchronizes given block using this channel's mutex.



1385
1386
1387
# File 'lib/bunny/channel.rb', line 1385

def synchronize(&block)
  @publishing_mutex.synchronize(&block)
end

#to_sString



1512
1513
1514
# File 'lib/bunny/channel.rb', line 1512

def to_s
  "#<#{self.class.name}:#{object_id} @id=#{self.number} @connection=#{@connection.to_s}>"
end

#topic(name, opts = {}) ⇒ Bunny::Exchange

Declares a topic exchange or looks it up in the cache of previously declared exchanges.

Options Hash (opts):

  • :durable (Boolean) — default: false

    Should the exchange be durable?

  • :auto_delete (Boolean) — default: false

    Should the exchange be automatically deleted when no longer in use?

  • :arguments (Hash) — default: {}

    Optional exchange arguments (used by RabbitMQ extensions)

See Also:



330
331
332
# File 'lib/bunny/channel.rb', line 330

def topic(name, opts = {})
  Exchange.new(self, :topic, name, opts)
end

#tx_commitAMQ::Protocol::Tx::CommitOk

Commits current transaction



1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
# File 'lib/bunny/channel.rb', line 1295

def tx_commit
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Commit.encode(@id))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_tx_commit_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_tx_commit_ok
end

#tx_rollbackAMQ::Protocol::Tx::RollbackOk

Rolls back current transaction



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
# File 'lib/bunny/channel.rb', line 1310

def tx_rollback
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Rollback.encode(@id))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_tx_rollback_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_tx_rollback_ok
end

#tx_selectAMQ::Protocol::Tx::SelectOk

Puts the channel into transaction mode (starts a transaction)



1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
# File 'lib/bunny/channel.rb', line 1279

def tx_select
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Select.encode(@id))
  Bunny::Timeout.timeout(read_write_timeout, ClientTimeout) do
    @last_tx_select_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!
  @tx_mode = true

  @last_tx_select_ok
end

#using_publisher_confirmations?Boolean

Returns true if this channel has Publisher Confirms enabled, false otherwise



1330
1331
1332
# File 'lib/bunny/channel.rb', line 1330

def using_publisher_confirmations?
  @next_publish_seq_no > 0
end

#wait_for_confirmsBoolean

Blocks calling thread until confirms are received for all currently unacknowledged published messages.



1371
1372
1373
1374
1375
1376
# File 'lib/bunny/channel.rb', line 1371

def wait_for_confirms
  @only_acks_received = true
  wait_on_confirms_continuations

  @only_acks_received
end