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:

conn = Bunny.new
conn.start

ch   = conn.create_channel

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.

ch = conn.create_channel
ch.close

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:

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:

Consumer and Message operations (basic.*) collapse

MAX_PREFETCH_COUNT =

prefetch_count is of type short in the protocol. MK.

(2 ** 16) - 1

Constant Summary collapse

DEFAULT_CONTENT_TYPE =
"application/octet-stream".freeze
DEFAULT_OUTSTANDING_CONFIRMS_LIMIT =

Default outstanding limit for publisher confirms with tracking. Batch size of 1000 provides optimal throughput per benchmarks.

1000
SHORTSTR_LIMIT =
255

Instance Attribute Summary collapse

Backwards compatibility with 0.8.0 collapse

Other settings 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, opts = {}) ⇒ Channel

Returns a new instance of Channel.

Parameters:

  • connection (Bunny::Session) (defaults to: nil)

    AMQP 0.9.1 connection

  • id (Integer) (defaults to: nil)

    Channel id, pass nil to make Bunny automatically allocate it

  • opts (HashMap) (defaults to: {})

    Additional options

Options Hash (opts):



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/bunny/channel.rb', line 181

def initialize(connection = nil, id = nil, opts = {})
  work_pool = opts.fetch(:work_pool, ConsumerWorkPool.new(1))

  @connection = connection
  @logger     = connection.logger
  @id         = id || @connection.next_channel_id

  # channel allocator is exhausted
  if @id < 0
    msg = "Cannot open a channel: max number of channels on connection reached. Connection channel_max value: #{@connection.channel_max}"
    @logger.error(msg)

    raise msg
  else
    @logger.debug { "Allocated channel id: #{@id}" }
  end

  @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

  @queue_mutex    = @connection.mutex_impl.new
  @exchange_mutex = @connection.mutex_impl.new

  @unconfirmed_set_mutex = @connection.mutex_impl.new

  # Publisher confirm tracking (initialized before reset_continuations)
  @confirms_tracking_enabled = false
  @outstanding_limit = nil
  @confirm_timeout = nil
  @throttle_publishes = false
  @per_message_continuations = {}
  @per_message_continuations_mutex = @connection.mutex_impl.new
  @outstanding_limit_cond = nil

  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
  @delivery_tag_offset = 0

  @uncaught_exception_handler = Proc.new do |e, consumer|
    @logger.error "Uncaught exception from consumer #{consumer.to_s}: #{e.inspect} @ #{e.backtrace[0]}"
  end

  @cancel_consumers_before_closing = false

  @last_consumer_tag = nil
  @last_consumer = nil
end

Instance Attribute Details

#cancel_consumers_before_closingObject (readonly)

Returns the value of attribute cancel_consumers_before_closing.



168
169
170
# File 'lib/bunny/channel.rb', line 168

def cancel_consumers_before_closing
  @cancel_consumers_before_closing
end

#confirm_timeoutInteger? (readonly)

Returns Timeout in milliseconds for waiting on publisher confirms.

Returns:

  • (Integer, nil)

    Timeout in milliseconds for waiting on publisher confirms



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

def confirm_timeout
  @confirm_timeout
end

#confirms_tracking_enabledBoolean (readonly)

Returns true if publisher confirm tracking is enabled.

Returns:

  • (Boolean)

    true if publisher confirm tracking is enabled



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

def confirms_tracking_enabled
  @confirms_tracking_enabled
end

#connectionBunny::Session (readonly)

Returns AMQP connection this channel was opened on.

Returns:



135
136
137
# File 'lib/bunny/channel.rb', line 135

def connection
  @connection
end

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

Returns Consumer instances declared on this channel.

Returns:

  • (Hash<String, Bunny::Consumer>)

    Consumer instances declared on this channel



161
162
163
# File 'lib/bunny/channel.rb', line 161

def consumers
  @consumers
end

#delivery_tag_offsetInteger (readonly)

This will be set to the current sequence index during automatic network failure recovery to keep the sequence monotonic for the user and abstract the reset from the protocol

Returns:

  • (Integer)

    Offset for the confirmations sequence index.



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

def delivery_tag_offset
  @delivery_tag_offset
end

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

Returns Exchange instances declared on this channel.

Returns:

  • (Hash<String, Bunny::Exchange>)

    Exchange instances declared on this channel



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

def exchanges
  @exchanges
end

#idInteger

Returns Channel id.

Returns:

  • (Integer)

    Channel id



133
134
135
# File 'lib/bunny/channel.rb', line 133

def id
  @id
end

#nacked_setSet<Integer> (readonly)

Returns Set of nacked message indexes that have been nacked.

Returns:

  • (Set<Integer>)

    Set of nacked message indexes that have been nacked



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

def nacked_set
  @nacked_set
end

#next_publish_seq_noInteger (readonly)

Returns Next publisher confirmations sequence index.

Returns:

  • (Integer)

    Next publisher confirmations sequence index



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

def next_publish_seq_no
  @next_publish_seq_no
end

#outstanding_limitInteger? (readonly)

Returns Maximum outstanding unconfirmed messages before throttling.

Returns:

  • (Integer, nil)

    Maximum outstanding unconfirmed messages before throttling



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

def outstanding_limit
  @outstanding_limit
end

#prefetch_countInteger (readonly)

Returns active basic.qos prefetch value.

Returns:

  • (Integer)

    active basic.qos prefetch value



164
165
166
# File 'lib/bunny/channel.rb', line 164

def prefetch_count
  @prefetch_count
end

#prefetch_globalInteger (readonly)

Returns active basic.qos prefetch global mode.

Returns:

  • (Integer)

    active basic.qos prefetch global mode



166
167
168
# File 'lib/bunny/channel.rb', line 166

def prefetch_global
  @prefetch_global
end

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

Returns Queue instances declared on this channel.

Returns:

  • (Hash<String, Bunny::Queue>)

    Queue instances declared on this channel



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

def queues
  @queues
end

#statusSymbol (readonly)

Returns Channel status (:opening, :open, :closed).

Returns:

  • (Symbol)

    Channel status (:opening, :open, :closed)



137
138
139
# File 'lib/bunny/channel.rb', line 137

def status
  @status
end

#unconfirmed_setSet<Integer> (readonly)

Returns Set of published message indexes that are currently unconfirmed.

Returns:

  • (Set<Integer>)

    Set of published message indexes that are currently unconfirmed



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

def unconfirmed_set
  @unconfirmed_set
end

#work_poolBunny::ConsumerWorkPool (readonly)

Returns Thread pool delivered messages are dispatched to.

Returns:



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

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.

Parameters:

  • delivery_tag (Integer)

    Delivery tag to acknowledge

  • multiple (Boolean) (defaults to: false)

    (false) Should all unacknowledged messages up to this be acknowledged as well?

See Also:



719
720
721
# File 'lib/bunny/channel.rb', line 719

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

#activeBoolean

Returns true if this channel is open.

Returns:

  • (Boolean)

    true if this channel is open



365
366
367
# File 'lib/bunny/channel.rb', line 365

def active
  open?
end

#add_consumer(queue_name, consumer_tag, no_ack, exclusive, arguments, &block) ⇒ Object

Parameters:

  • queue_name (String)
  • consumer_tag (String)
  • no_ack (Boolean)

    true means automative acknowledgement mode

  • exclusive (Boolean)
  • arguments (Hash)


2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
# File 'lib/bunny/channel.rb', line 2104

def add_consumer(queue_name, consumer_tag, no_ack, exclusive, arguments, &block)
  @consumer_mutex.synchronize do
    c = Consumer.new(self, queue_name, consumer_tag, no_ack, exclusive, arguments)
    c.on_delivery(&block) if block
    @consumers[consumer_tag] = c
    if @last_consumer_tag == consumer_tag
      @last_consumer = c
    end
    c
  end
  record_consumer_with(self, consumer_tag,
      queue_name,
      block,
      !no_ack,
      exclusive,
      arguments)
end

#any_consumers?Boolean

Returns true if there are consumers on this channel.

Returns:

  • (Boolean)

    true if there are consumers on this channel



1316
1317
1318
# File 'lib/bunny/channel.rb', line 1316

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

#basic_ack(delivery_tag, multiple = false) ⇒ 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.to_i)
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", manual_ack: true)
ch.basic_ack(delivery_info.delivery_tag.to_i)

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", manual_ack: true)
_, _, payload2 = ch.basic_get("bunny.examples.queue3", manual_ack: true)
delivery_info, properties, payload3 = ch.basic_get("bunny.examples.queue3", manual_ack: true)
# ack all fetched messages up to payload3
ch.basic_ack(delivery_info.delivery_tag.to_i, true)

Parameters:

  • delivery_tag (Integer)

    Delivery tag obtained from delivery info

  • multiple (Boolean) (defaults to: false)

    Should all deliveries up to this one be acknowledged?

Returns:

  • (NilClass)

    nil

See Also:



1091
1092
1093
1094
1095
1096
1097
1098
# File 'lib/bunny/channel.rb', line 1091

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

    nil
  end
end

#basic_cancel(consumer_tag, opts = {}) ⇒ 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.

Parameters:

  • consumer_tag (String)

    Consumer tag (unique identifier) to cancel

  • opts (Hash) (defaults to: {})

    ({}) Optional arguments

Options Hash (opts):

  • :no_wait (Boolean) — default: false

    if set to true, this method won't receive a response and will immediately return nil

Returns:

  • (AMQ::Protocol::Basic::CancelOk, nil)

    RabbitMQ response or nil, if the no_wait option is used

See Also:



1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
# File 'lib/bunny/channel.rb', line 1294

def basic_cancel(consumer_tag, opts = {})
  no_wait = opts.fetch(:no_wait, false)
  @connection.send_frame(AMQ::Protocol::Basic::Cancel.encode(@id, consumer_tag, no_wait))

  if no_wait
    @last_basic_cancel_ok = nil
  else
    with_continuation_timeout do
      @last_basic_cancel_ok = wait_on_continuations
    end
  end

  # reduces thread usage for channels that don't have any
  # consumers
  @work_pool.shutdown(true) unless self.any_consumers?
  self.delete_recorded_consumer(consumer_tag)

  @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.

Parameters:

  • queue (String)

    Queue to consume from

  • consumer_tag (String) (defaults to: generate_consumer_tag)

    Consumer tag (unique identifier), generated by Bunny by default

  • no_ack (Boolean) (defaults to: false)

    (false) If true, delivered messages will be automatically acknowledged. If false, manual acknowledgements will be necessary.

  • exclusive (Boolean) (defaults to: false)

    (false) Should this consumer be exclusive?

  • arguments (Hash) (defaults to: nil)

    (nil) Optional arguments that may be used by RabbitMQ extensions, etc

Returns:

  • (AMQ::Protocol::Basic::ConsumeOk)

    RabbitMQ response

See Also:



1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# File 'lib/bunny/channel.rb', line 1178

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 = queue.is_a?(Bunny::Queue) ? queue.name : queue

  # 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
    with_continuation_timeout 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)
    # #add_consumer records a consumer, make sure to undo it here. MK.
    delete_recorded_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.

Parameters:

  • consumer (Bunny::Consumer)

    Consumer to register. It should already have queue name, consumer tag and other attributes set.

Returns:

  • (AMQ::Protocol::Basic::ConsumeOk)

    RabbitMQ response

See Also:



1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
# File 'lib/bunny/channel.rb', line 1232

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
    with_continuation_timeout 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)
  record_consumer_with(self, @last_basic_consume_ok.consumer_tag,
    consumer.queue_name,
    consumer,
    consumer.manual_acknowledgement?,
    consumer.exclusive,
    consumer.arguments)

  raise_if_continuation_resulted_in_a_channel_error!

  @last_basic_consume_ok
end

#basic_get(queue, opts = { manual_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", manual_ack: true)
ch.acknowledge(delivery_info.delivery_tag)

Parameters:

  • queue (String)

    Queue name

  • opts (Hash) (defaults to: { manual_ack: true })

    Options

Options Hash (opts):

  • :ack (Boolean) — default: true

    [DEPRECATED] Use :manual_ack instead

  • :manual_ack (Boolean) — default: true

    Will this message be acknowledged manually?

Returns:

  • (Array)

    A triple of delivery info, message properties and message content

See Also:



920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# File 'lib/bunny/channel.rb', line 920

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

  unless opts[:ack].nil?
    warn "[DEPRECATION] `:ack` is deprecated.  Please use `:manual_ack` instead."
    opts[:manual_ack] = opts[:ack]
  end

  @connection.send_frame(AMQ::Protocol::Basic::Get.encode(@id, queue, !(opts[:manual_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?
                              begin
                                wait_on_basic_get_continuations
                              rescue Timeout::Error => e
                                raise_if_continuation_resulted_in_a_channel_error!
                                raise e
                              end
                            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", manual_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", manual_ack: true)
_, _, payload2 = ch.basic_get("bunny.examples.queue3", manual_ack: true)
delivery_info, properties, payload3 = ch.basic_get("bunny.examples.queue3", manual_ack: true)
# requeue all fetched messages up to payload3
ch.basic_nack(delivery_info.delivery_tag, true, true)

Parameters:

  • delivery_tag (Integer)

    Delivery tag obtained from delivery info

  • requeue (Boolean) (defaults to: false)

    Should the message be requeued?

  • multiple (Boolean) (defaults to: false)

    Should all deliveries up to this one be rejected/requeued?

Returns:

  • (NilClass)

    nil

See Also:



1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/bunny/channel.rb', line 1153

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

    nil
  end
end

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

Publishes a message using basic.publish AMQP 0.9.1 method.

Parameters:

  • payload (String)

    Message payload. It will never be modified by Bunny or RabbitMQ in any way.

  • exchange (String)

    Exchange to publish to

  • routing_key (String)

    Routing key

  • opts (Hash) (defaults to: {})

    Publishing options

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

Returns:

Raises:

  • (ArgumentError)


770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/bunny/channel.rb', line 770

def basic_publish(payload, exchange, routing_key, opts = {})
  raise_if_no_longer_open!
  raise ArgumentError, "routing key cannot be longer than #{SHORTSTR_LIMIT} characters" if routing_key && routing_key.size > SHORTSTR_LIMIT

  exchange_name = exchange.is_a?(Bunny::Exchange) ? exchange.name : exchange

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

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

  seq_no = nil
  continuation = nil

  if @next_publish_seq_no > 0
    @unconfirmed_set_mutex.synchronize do
      # With outstanding_limit: wait for slot if at the limit
      wait_for_outstanding_slot_locked if @throttle_publishes

      seq_no = @next_publish_seq_no
      @unconfirmed_set.add(seq_no)
      @next_publish_seq_no += 1

      # Only create per-message continuation when blocking individually (no limit)
      if @confirms_tracking_enabled && !@throttle_publishes
        continuation = new_continuation
        @per_message_continuations_mutex.synchronize do
          @per_message_continuations[seq_no] = continuation
        end
      end
    end
  end

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

  wait_for_publish_confirm(seq_no, continuation) if continuation

  self
end

#basic_publish_batch(payloads, exchange, routing_key, opts = {}) ⇒ self

Publishes multiple messages in a batch with a single mutex acquisition. More efficient than calling basic_publish repeatedly when using publisher confirms with tracking. Recommended batch sizes: 500-3000.

Examples:

Batch publishing with confirms

ch.confirm_select(tracking: true)
messages = 100.times.map { |i| "message #{i}" }
ch.basic_publish_batch(messages, "", queue.name)

Parameters:

  • payloads (Array<String>)

    Array of message payloads to publish

  • exchange (String, Bunny::Exchange)

    Exchange name or object

  • routing_key (String)

    Routing key

  • opts (Hash) (defaults to: {})

    Publishing options (applied to all messages)

Returns:

  • (self)

Raises:

  • (ArgumentError)


839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
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
# File 'lib/bunny/channel.rb', line 839

def basic_publish_batch(payloads, exchange, routing_key, opts = {})
  raise_if_no_longer_open!
  raise ArgumentError, "payloads must be an Array" unless payloads.is_a?(Array)
  raise ArgumentError, "routing key cannot be longer than #{SHORTSTR_LIMIT} characters" if routing_key && routing_key.size > SHORTSTR_LIMIT
  return self if payloads.empty?

  exchange_name = exchange.is_a?(Bunny::Exchange) ? exchange.name : exchange

  mode = opts.fetch(:persistent, true) ? 2 : 1
  opts = opts.dup
  opts[:delivery_mode] ||= mode
  opts[:content_type]  ||= DEFAULT_CONTENT_TYPE
  opts[:priority]      ||= 0

  batch_size = payloads.size

  if @next_publish_seq_no > 0
    @unconfirmed_set_mutex.synchronize do
      # With throttling: wait until we have room for the batch
      if @throttle_publishes
        limit = @outstanding_limit
        target = [limit - batch_size, 0].max
        timeout_sec = (@confirm_timeout || @connection.continuation_timeout) / 1000.0
        deadline = nil

        while @unconfirmed_set.size > target
          raise_if_no_longer_open!
          deadline ||= Bunny::Timestamp.monotonic + timeout_sec
          remaining = deadline - Bunny::Timestamp.monotonic
          raise Timeout::Error, "Timed out waiting for publisher confirms (batch: #{batch_size}, limit: #{limit})" if remaining <= 0
          @outstanding_limit_cond.wait(remaining)
        end
      end

      # Register all sequence numbers at once
      start_seq = @next_publish_seq_no
      batch_size.times { |i| @unconfirmed_set.add(start_seq + i) }
      @next_publish_seq_no = start_seq + batch_size
    end
  end

  # Encode all messages into a single buffer and write once
  data = +""
  payloads.each do |payload|
    frames = AMQ::Protocol::Basic::Publish.encode(@id,
      payload,
      opts,
      exchange_name,
      routing_key,
      opts[:mandatory],
      false,
      @frame_max)
    frames.each { |frame| data << frame.encode }
  end
  @connection.send_raw_without_timeout(data, self)

  self
end

#basic_qos(prefetch_count, global = false) ⇒ AMQ::Protocol::Basic::QosOk Also known as: prefetch

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

Parameters:

  • prefetch_count (Integer)

    How many messages can consumers on this channel be given at a time (before they have to acknowledge or reject one of the earlier received messages)

  • global (Boolean) (defaults to: false)

    Whether to use global mode for prefetch:

    • false: per-consumer
    • true: per-channel Note that the default value (+false+) hasn't actually changed, but previous documentation described that as meaning per-channel and unsupported in RabbitMQ, whereas it now actually appears to mean per-consumer and supported (https://www.rabbitmq.com/consumer-prefetch.html).

Returns:

  • (AMQ::Protocol::Basic::QosOk)

    RabbitMQ response

Raises:

  • (ArgumentError)

See Also:



971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
# File 'lib/bunny/channel.rb', line 971

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 ArgumentError.new("prefetch count must be no greater than #{MAX_PREFETCH_COUNT}, given: #{prefetch_count}") if prefetch_count > MAX_PREFETCH_COUNT
  raise_if_no_longer_open!

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

  with_continuation_timeout do
    @last_basic_qos_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @prefetch_count  = prefetch_count
  @prefetch_global = global

  @last_basic_qos_ok
end

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

Redeliver unacknowledged messages

Parameters:

  • requeue (Boolean)

    Should messages be requeued?

Returns:

  • (AMQ::Protocol::Basic::RecoverOk)

    RabbitMQ response



995
996
997
998
999
1000
1001
1002
1003
1004
1005
# File 'lib/bunny/channel.rb', line 995

def basic_recover(requeue)
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Basic::Recover.encode(@id, requeue))
  with_continuation_timeout 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 = false) ⇒ 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|
  # reject 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", manual_ack: true)
ch.basic_reject(delivery_info.delivery_tag, true)

Parameters:

  • delivery_tag (Integer)

    Delivery tag obtained from delivery info

  • requeue (Boolean) (defaults to: false)

    Should the message be requeued?

Returns:

  • (NilClass)

    nil

See Also:



1045
1046
1047
1048
1049
1050
# File 'lib/bunny/channel.rb', line 1045

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

  nil
end

#can_accept_queue_declare_ok?(method) ⇒ Boolean

Returns:

  • (Boolean)


2128
2129
2130
2131
# File 'lib/bunny/channel.rb', line 2128

def can_accept_queue_declare_ok?(method)
  @pending_queue_declare_name == method.queue ||
    pending_server_named_queue_declaration?
end

#cancel_consumers_before_closing!Object



389
390
391
# File 'lib/bunny/channel.rb', line 389

def cancel_consumers_before_closing!
  @cancel_consumers_before_closing = true
end

#cancel_consumers_before_closing?Boolean

Returns:

  • (Boolean)


393
394
395
# File 'lib/bunny/channel.rb', line 393

def cancel_consumers_before_closing?
  !!@cancel_consumers_before_closing
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.

Returns:

  • (AMQ::Protocol::Channel::FlowOk)

    RabbitMQ response

See Also:



1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
# File 'lib/bunny/channel.rb', line 1763

def channel_flow(active)
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Channel::Flow.encode(@id, active))
  with_continuation_timeout do
    @last_channel_flow_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!

  @last_channel_flow_ok
end

#channel_level_exception_after_operation_that_has_no_response?(method) ⇒ Boolean

Returns:

  • (Boolean)


2234
2235
2236
# File 'lib/bunny/channel.rb', line 2234

def channel_level_exception_after_operation_that_has_no_response?(method)
  method.unknown_delivery_tag? || method.delivery_ack_timeout? || method.message_too_large?
end

#clientBunny::Session

Returns Connection this channel was opened on.

Returns:



370
371
372
# File 'lib/bunny/channel.rb', line 370

def client
  @connection
end

#closeObject

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



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/bunny/channel.rb', line 272

def close
  # see bunny#528
  raise_if_no_longer_open!

  # This is a best-effort attempt to cancel all consumers before closing the channel.
  # Retries are extremely unlikely to succeed, and the channel itself is about to be closed,
  # so we don't bother retrying.
  if self.cancel_consumers_before_closing?
   # cancelling a consumer involves using the same mutex, so avoid holding the lock
    keys = @consumer_mutex.synchronize { @consumers.keys }
    keys.each do |ctag|
      begin
        self.basic_cancel(ctag)
      rescue Bunny::Exception
        # ignore
      rescue Bunny::ClientTimeout
        # ignore
      end
    end
  end

  @connection.close_channel(self)
  @status = :closed
  @work_pool.shutdown
  maybe_kill_consumer_work_pool!
end

#closed?Boolean

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

Returns:

  • (Boolean)

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



336
337
338
# File 'lib/bunny/channel.rb', line 336

def closed?
  @status == :closed
end

#configure(&block) ⇒ Object



383
384
385
386
387
# File 'lib/bunny/channel.rb', line 383

def configure(&block)
  block.call(self) if block_given?

  self
end

#confirm_select(callback = nil, tracking: false, outstanding_limit: nil, confirm_timeout: nil) ⇒ AMQ::Protocol::Confirm::SelectOk

Enables publisher confirms for the channel.

Parameters:

  • callback (Proc) (defaults to: nil)

    Optional callback invoked for each confirm. Receives (delivery_tag, multiple, nack).

  • tracking (Boolean) (defaults to: false)

    When true, basic_publish blocks until the broker confirms receipt. Raises Bunny::MessageNacked if the message is nacked.

  • outstanding_limit (Integer) (defaults to: nil)

    Max unconfirmed messages before basic_publish blocks. Defaults to 1000 when tracking: true (optimal for throughput). Pass explicit value to override.

  • confirm_timeout (Integer) (defaults to: nil)

    Timeout in ms for confirms. Defaults to connection's continuation_timeout.

Returns:

  • (AMQ::Protocol::Confirm::SelectOk)

    RabbitMQ response

Raises:

  • (ArgumentError)

See Also:



1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
# File 'lib/bunny/channel.rb', line 1860

def confirm_select(callback = nil, tracking: false, outstanding_limit: nil, confirm_timeout: nil)
  raise_if_no_longer_open!
  raise ArgumentError, "outstanding_limit requires tracking: true" if outstanding_limit && !tracking
  raise ArgumentError, "outstanding_limit must be positive" if outstanding_limit && outstanding_limit < 1
  raise ArgumentError, "confirm_timeout must be positive" if confirm_timeout && confirm_timeout < 1

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

  @confirms_callback = callback
  @confirms_tracking_enabled = tracking
  # Default to optimal limit when tracking enabled (avoids per-message mutex)
  @outstanding_limit = outstanding_limit || (tracking ? DEFAULT_OUTSTANDING_CONFIRMS_LIMIT : nil)
  @confirm_timeout = confirm_timeout

  # Cache combined check for fast path in basic_publish
  @throttle_publishes = tracking && @outstanding_limit

  if @outstanding_limit && !@outstanding_limit_cond
    @outstanding_limit_cond = @unconfirmed_set_mutex.new_cond
  end

  @connection.send_frame(AMQ::Protocol::Confirm::Select.encode(@id, false))
  with_continuation_timeout do
    @last_confirm_select_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!
  @last_confirm_select_ok
end

#connection_closed!Object



341
342
343
# File 'lib/bunny/channel.rb', line 341

def connection_closed!
  @status = :closed
end

#default_exchangeObject

Provides access to the default exchange



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

def default_exchange
  @default_exchange ||= Exchange.default(self)
end

#delayed_queue(name, opts = {}) ⇒ Bunny::Queue

Declares a Tanzu RabbitMQ delayed queue (a durable, replicated queue type). This queue type must be durable, non-exclusive, and non-auto-delete.

Parameters:

  • name (String)

    Queue name. Empty (server-generated) names are not supported by this method.

  • opts (Hash) (defaults to: {})

    Queue properties

Options Hash (opts):

  • :delayed_retry_type (String) — default: "all"

    Retry strategy: "all", "failed", or "returned"

  • :delayed_retry_min (Integer) — default: nil

    Minimum retry delay in milliseconds

  • :delayed_retry_max (Integer) — default: nil

    Maximum retry delay in milliseconds

  • :arguments (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

Raises:

  • (ArgumentError)

See Also:



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/bunny/channel.rb', line 585

def delayed_queue(name, opts = {})
  raise ArgumentError, "delayed queue name must not be nil" if name.nil?
  raise ArgumentError, "delayed queue name must not be empty" if name.empty?

  args = opts[:arguments] || {}
  args[Bunny::Queue::XArgs::DELAYED_RETRY_TYPE] = opts[:delayed_retry_type] if opts[:delayed_retry_type]
  args[Bunny::Queue::XArgs::DELAYED_RETRY_MIN]  = opts[:delayed_retry_min]  if opts[:delayed_retry_min]
  args[Bunny::Queue::XArgs::DELAYED_RETRY_MAX]  = opts[:delayed_retry_max]  if opts[:delayed_retry_max]

  final_opts = opts.merge(arguments: args)
  final_opts.delete(:delayed_retry_type)
  final_opts.delete(:delayed_retry_min)
  final_opts.delete(:delayed_retry_max)

  durable_queue(name, Bunny::Queue::Types::DELAYED, final_opts)
end

#delete_recorded_consumer(consumer_tag) ⇒ Object

Parameters:

  • consumer_tag (String)


2644
2645
2646
# File 'lib/bunny/channel.rb', line 2644

def delete_recorded_consumer(consumer_tag)
  @connection.delete_recorded_consumer(consumer_tag)
end

#delete_recorded_exchange(exchange) ⇒ Object

Parameters:



2580
2581
2582
# File 'lib/bunny/channel.rb', line 2580

def delete_recorded_exchange(exchange)
  @connection.delete_recorded_exchange(exchange)
end

#delete_recorded_exchange_binding(ch, source_name, destination_name, routing_key, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • source_name (String)
  • destination_name (String)
  • routing_key (String)
  • arguments (Hash)


2626
2627
2628
# File 'lib/bunny/channel.rb', line 2626

def delete_recorded_exchange_binding(ch, source_name, destination_name, routing_key, arguments)
  @connection.delete_recorded_exchange_binding(ch, source_name, destination_name, routing_key, arguments)
end

#delete_recorded_exchange_named(name) ⇒ Object

Parameters:

  • name (String)


2586
2587
2588
# File 'lib/bunny/channel.rb', line 2586

def delete_recorded_exchange_named(name)
  @connection.delete_recorded_exchange_named(name)
end

#delete_recorded_queue_binding(ch, exchange_name, queue_name, routing_key, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • exchange_name (String)
  • queue_name (String)
  • routing_key (String)
  • arguments (Hash)


2606
2607
2608
# File 'lib/bunny/channel.rb', line 2606

def delete_recorded_queue_binding(ch, exchange_name, queue_name, routing_key, arguments)
  @connection.delete_recorded_queue_binding(ch, exchange_name, queue_name, routing_key, arguments)
end

#delete_recorded_queue_named(name) ⇒ Object

Parameters:

  • name (String)


2540
2541
2542
# File 'lib/bunny/channel.rb', line 2540

def delete_recorded_queue_named(name)
  @connection.delete_recorded_queue_named(name)
end

#delete_recoreded_queue(queue) ⇒ Object

Parameters:



2534
2535
2536
# File 'lib/bunny/channel.rb', line 2534

def delete_recoreded_queue(queue)
  @connection.delete_recorded_queue(queue)
end

#deliver_to_consumer(consumer, basic_deliver, properties, content) ⇒ Object



2270
2271
2272
2273
2274
2275
2276
# File 'lib/bunny/channel.rb', line 2270

def deliver_to_consumer(consumer, basic_deliver, properties, content)
  begin
    consumer.call(DeliveryInfo.new(basic_deliver, consumer, self), MessageProperties.new(properties), content)
  rescue StandardError => e
    @uncaught_exception_handler.call(e, consumer) if @uncaught_exception_handler
  end
end

#deregister_exchange(exchange) ⇒ Object

Parameters:



2552
2553
2554
# File 'lib/bunny/channel.rb', line 2552

def deregister_exchange(exchange)
  @queue_mutex.synchronize { @exchanges.delete(exchange.name) }
end

#deregister_exchange_named(name) ⇒ Object

Parameters:

  • name (String)


2558
2559
2560
# File 'lib/bunny/channel.rb', line 2558

def deregister_exchange_named(name)
  @queue_mutex.synchronize { @exchanges.delete(name) }
end

#deregister_queue(queue) ⇒ Object

Parameters:



2505
2506
2507
# File 'lib/bunny/channel.rb', line 2505

def deregister_queue(queue)
  @queue_mutex.synchronize { @queues.delete(queue.name) }
end

#deregister_queue_named(name) ⇒ Object

Parameters:

  • name (Bunny::String)


2511
2512
2513
# File 'lib/bunny/channel.rb', line 2511

def deregister_queue_named(name)
  @queue_mutex.synchronize { @queues.delete(name) }
end

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

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

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Exchange parameters

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)

Returns:

See Also:



437
438
439
# File 'lib/bunny/channel.rb', line 437

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

#durable_queue(name, type = "classic", opts = {}) ⇒ Bunny::Queue

Declares a new server-named queue that is automatically deleted when the connection is closed.

Parameters:

  • name (String)

    Queue name. Empty (server-generated) names are not supported by this method.

  • opts (Hash) (defaults to: {})

    Queue properties and other options. Durability, exclusivity, auto-deletion options will be ignored.

Options Hash (opts):

  • :arguments (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

Raises:

  • (ArgumentError)

See Also:



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/bunny/channel.rb', line 642

def durable_queue(name, type = "classic", opts = {})
  raise ArgumentError, "queue name must not be nil" if name.nil?
  raise ArgumentError, "queue name must not be empty (server-named durable queues do not make sense)" if name.empty?

  final_opts = opts.merge(
    type:        type,
    durable:     true,
    # exclusive or auto-delete QQs do not make much sense
    exclusive:   false,
    auto_delete: false
  )
  q = find_queue(name) || Bunny::Queue.new(self, name, final_opts)

  record_queue(q)
  register_queue(q)
end

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

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

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Exchange parameters

Options Hash (opts):

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

    Exchange type, e.g. :fanout or "x-consistent-hash" or "x-modulus-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

Returns:

See Also:



498
499
500
# File 'lib/bunny/channel.rb', line 498

def exchange(name, opts = {})
  find_exchange(name) || 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.

Parameters:

  • source (String)

    Source exchange name

  • destination (String)

    Destination exchange name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

Returns:

  • (AMQ::Protocol::Exchange::BindOk)

    RabbitMQ response

See Also:



1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
# File 'lib/bunny/channel.rb', line 1667

def exchange_bind(source, destination, opts = {})
  result = self.exchange_bind_without_recording_topology(source, destination, opts)

  source_name = source.is_a?(Bunny::Exchange) ? source.name : source
  destination_name = destination.is_a?(Bunny::Exchange) ? destination.name : destination
  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]
  self.record_exchange_binding_with(self, source_name, destination_name, rk, args)

  result
end

#exchange_bind_without_recording_topology(source, destination, opts = {}) ⇒ Object

We need this bypassing topology version to avoid modifying the collections as we iterate over them during topology recovery.



1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
# File 'lib/bunny/channel.rb', line 1682

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

  source_name = source.is_a?(Bunny::Exchange) ? source.name : source

  destination_name = destination.is_a?(Bunny::Exchange) ? destination.name : destination

  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]
  @connection.send_frame(AMQ::Protocol::Exchange::Bind.encode(@id,
      destination_name,
      source_name,
      rk,
      false,
      args))
  with_continuation_timeout do
    @last_exchange_bind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  self.record_exchange_binding_with(self, source_name, destination_name, rk, args)

  @last_exchange_bind_ok
end

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

Declares a exchange using exchange.declare AMQP 0.9.1 method.

Parameters:

  • name (String)

    The name of the exchange. Note that LF and CR characters will be stripped from the value.

  • type (String, Symbol)

    Exchange type, e.g. :fanout or :topic

  • opts (Hash) (defaults to: {})

    Exchange properties

Options Hash (opts):

  • durable (Boolean) — default: false

    Should information about this exchange 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 exchange 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.

Returns:

  • (AMQ::Protocol::Exchange::DeclareOk)

    RabbitMQ response

See Also:



1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
# File 'lib/bunny/channel.rb', line 1561

def exchange_declare(name, type, opts = {})
  result = self.exchange_declare_without_recording_topology(name, type, opts)

  # strip trailing new line and carriage returns
  # just like RabbitMQ does
  safe_name = name.gsub(/[\r\n]/, "")
  passive = opts.fetch(:passive, false)
  durable = opts.fetch(:durable, false)
  auto_delete = opts.fetch(:auto_delete, false)
  args = opts[:arguments]
  self.record_exchange_with(self,
    safe_name,
    type.to_s,
    durable,
    auto_delete,
    args) unless passive

  result
end

#exchange_declare_without_recording_topology(name, type, opts = {}) ⇒ Object

We need this bypassing topology version to avoid modifying the collections as we iterate over them during topology recovery.

Parameters:

  • name (String)

    The name of the exchange. Note that LF and CR characters will be stripped from the value.

  • type (String, Symbol)

    Exchange type, e.g. :fanout or :topic

  • opts (Hash) (defaults to: {})

    Exchange properties

Options Hash (opts):

  • durable (Boolean) — default: false

    Should information about this exchange 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 exchange 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.



1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
# File 'lib/bunny/channel.rb', line 1595

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

  # strip trailing new line and carriage returns
  # just like RabbitMQ does
  safe_name = name.gsub(/[\r\n]/, "")
  passive = opts.fetch(:passive, false)
  durable = opts.fetch(:durable, false)
  auto_delete = opts.fetch(:auto_delete, false)
  args = opts[:arguments]

  @connection.send_frame(AMQ::Protocol::Exchange::Declare.encode(@id,
      safe_name,
      type.to_s,
      passive,
      durable,
      auto_delete,
      opts.fetch(:internal, false),
      opts.fetch(:no_wait, false),
      args))
  with_continuation_timeout 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

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • if_unused (Boolean) — default: false

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

Returns:

  • (AMQ::Protocol::Exchange::DeleteOk)

    RabbitMQ response

See Also:



1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'lib/bunny/channel.rb', line 1634

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

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

  raise_if_continuation_resulted_in_a_channel_error!
  self.delete_recorded_exchange_named(name)
  self.deregister_exchange_named(name)

  @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.

Parameters:

  • source (String)

    Source exchange name

  • destination (String)

    Destination exchange name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

Returns:

  • (AMQ::Protocol::Exchange::UnbindOk)

    RabbitMQ response

See Also:



1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
# File 'lib/bunny/channel.rb', line 1722

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

  source_name = source.is_a?(Bunny::Exchange) ? source.name : source

  destination_name = destination.is_a?(Bunny::Exchange) ? destination.name : destination

  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]
  @connection.send_frame(AMQ::Protocol::Exchange::Unbind.encode(@id,
      destination_name,
      source_name,
      rk,
      false,
      args))
  with_continuation_timeout do
    @last_exchange_unbind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  self.delete_recorded_exchange_binding(self, source_name, destination_name, rk, args)

  @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.

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Exchange parameters

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)

Returns:

See Also:



419
420
421
# File 'lib/bunny/channel.rb', line 419

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

#find_exchange(name) ⇒ Object

Parameters:

  • name (String)


2493
2494
2495
# File 'lib/bunny/channel.rb', line 2493

def find_exchange(name)
  @exchange_mutex.synchronize { @exchanges[name] }
end

#find_queue(name) ⇒ Object

Parameters:

  • name (String)


2487
2488
2489
# File 'lib/bunny/channel.rb', line 2487

def find_queue(name)
  @queue_mutex.synchronize { @queues[name] }
end

#flow(active) ⇒ Object

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

Parameters:

  • active (Boolean)

    Should messages to consumers on this channel be delivered?



682
683
684
# File 'lib/bunny/channel.rb', line 682

def flow(active)
  channel_flow(active)
end

#frame_sizeObject



375
376
377
# File 'lib/bunny/channel.rb', line 375

def frame_size
  @connection.frame_max
end

#generate_consumer_tag(prefix = "bunny") ⇒ String

Unique string supposed to be used as a consumer tag.

Returns:

  • (String)

    Unique string.



1925
1926
1927
1928
# File 'lib/bunny/channel.rb', line 1925

def generate_consumer_tag(prefix = "bunny")
  t = Bunny::Timestamp.now
  "#{prefix}-#{t.to_i * 1000}-#{Kernel.rand(999_999_999_999)}"
end

#handle_ack_or_nack(delivery_tag_before_offset, multiple, nack) ⇒ Object

Handle delivery tag offset calculations to keep the the delivery tag monotonic after a reset due to automatic network failure recovery. @unconfirmed_set contains indices already offsetted.



2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
# File 'lib/bunny/channel.rb', line 2292

def handle_ack_or_nack(delivery_tag_before_offset, multiple, nack)
  @unconfirmed_set_mutex.synchronize do
    delivery_tag          = delivery_tag_before_offset + @delivery_tag_offset
    confirmed_range_start = multiple ? @unconfirmed_set.min : delivery_tag
    confirmed_range_end   = delivery_tag
    confirmed_range       = (confirmed_range_start..confirmed_range_end)

    if nack
      @nacked_set.merge(@unconfirmed_set & confirmed_range)
    end

    @unconfirmed_set.subtract(confirmed_range)

    @only_acks_received = (@only_acks_received && !nack)

    @confirms_continuations.push(true) if @unconfirmed_set.empty?

    # Signal per-message continuations (only used when tracking without limit)
    if @confirms_tracking_enabled && !@throttle_publishes
      to_signal = []
      @per_message_continuations_mutex.synchronize do
        @per_message_continuations.each do |tag, cont|
          to_signal << cont if tag >= confirmed_range_start && tag <= confirmed_range_end
        end
      end
      result = nack ? :nack : :ack
      to_signal.each { |c| c.push(result) }
    end

    # Wake publisher(s) waiting for outstanding limit slot
    # Use broadcast since "multiple" acks can free many slots at once
    @outstanding_limit_cond&.broadcast if @throttle_publishes

    if @confirms_callback
      confirmed_range.each { |tag| @confirms_callback.call(tag, false, nack) }
    end
  end
end

#handle_basic_get_empty(basic_get_empty) ⇒ Object



2245
2246
2247
# File 'lib/bunny/channel.rb', line 2245

def handle_basic_get_empty(basic_get_empty)
  @basic_get_continuations.push([nil, nil, nil])
end

#handle_basic_get_ok(basic_get_ok, properties, content) ⇒ Object



2239
2240
2241
2242
# File 'lib/bunny/channel.rb', line 2239

def handle_basic_get_ok(basic_get_ok, properties, content)
  basic_get_ok.delivery_tag = basic_get_ok.delivery_tag
  @basic_get_continuations.push([basic_get_ok, properties, content])
end

#handle_basic_return(basic_return, properties, content) ⇒ Object



2279
2280
2281
2282
2283
2284
2285
2286
2287
# File 'lib/bunny/channel.rb', line 2279

def handle_basic_return(basic_return, properties, content)
  x = find_exchange(basic_return.exchange)

  if x
    x.handle_return(ReturnInfo.new(basic_return), MessageProperties.new(properties), content)
  else
    @logger.warn "Exchange #{basic_return.exchange} is not in channel #{@id}'s cache! Dropping returned message!"
  end
end

#handle_frameset(basic_deliver, properties, content) ⇒ Object



2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
# File 'lib/bunny/channel.rb', line 2250

def handle_frameset(basic_deliver, properties, content)
  tag = basic_deliver.consumer_tag
  if @last_consumer_tag == tag
    consumer = @last_consumer
  else
    consumer = @consumers[tag]
    @last_consumer_tag = tag
    @last_consumer = consumer
  end

  if consumer
    @work_pool.submit do
      deliver_to_consumer(consumer, basic_deliver, properties, content)
    end
  else
    @logger.warn "No consumer for tag #{basic_deliver.consumer_tag} on channel #{@id}!"
  end
end

#handle_method(method) ⇒ Object



2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
# File 'lib/bunny/channel.rb', line 2134

def handle_method(method)
  @logger.debug { "Channel#handle_frame on channel #{@id}: #{method.inspect}" }
  case method
  when AMQ::Protocol::Queue::DeclareOk then
    # safeguard against late arrivals of responses and
    # so on, see ruby-amqp/bunny#558
    if can_accept_queue_declare_ok?(method)
      @continuations.push(method)
    else
      if !pending_server_named_queue_declaration?
        # this response is for an outdated/overwritten
        # queue.declare, drop it
        @logger.warn "Received a queue.declare-ok response for a mismatching queue (#{method.queue} instead of #{@pending_queue_declare_name}) on channel #{@id}, possibly due to concurrent channel use or a timeout, ignoring it"
      end
    end
  when AMQ::Protocol::Queue::DeleteOk then
    @continuations.push(method)
  when AMQ::Protocol::Queue::PurgeOk then
    @continuations.push(method)
  when AMQ::Protocol::Queue::BindOk then
    @continuations.push(method)
  when AMQ::Protocol::Queue::UnbindOk then
    @continuations.push(method)
  when AMQ::Protocol::Exchange::BindOk then
    @continuations.push(method)
  when AMQ::Protocol::Exchange::UnbindOk then
    @continuations.push(method)
  when AMQ::Protocol::Exchange::DeclareOk then
    @continuations.push(method)
  when AMQ::Protocol::Exchange::DeleteOk then
    @continuations.push(method)
  when AMQ::Protocol::Basic::QosOk then
    @continuations.push(method)
  when AMQ::Protocol::Basic::RecoverOk then
    @continuations.push(method)
  when AMQ::Protocol::Channel::FlowOk then
    @continuations.push(method)
  when AMQ::Protocol::Basic::ConsumeOk then
    @continuations.push(method)
  when AMQ::Protocol::Basic::Cancel then
    if consumer = @consumers[method.consumer_tag]
      @work_pool.submit do
        begin
          if recovers_cancelled_consumers?
            consumer.handle_cancellation(method)
            @logger.info "Automatically recovering cancelled consumer #{consumer.consumer_tag} on queue #{consumer.queue_name}"

            consume_with(consumer)
          else
            @consumers.delete(method.consumer_tag)
            if @last_consumer_tag == method.consumer_tag
              @last_consumer_tag = nil
              @last_consumer = nil
            end
            consumer.handle_cancellation(method)
          end
        rescue Exception => e
          @logger.error "Got exception when notifying consumer #{method.consumer_tag} about cancellation!"
          @uncaught_exception_handler.call(e, consumer) if @uncaught_exception_handler
        end
      end
    else
      @logger.warn "No consumer for tag #{method.consumer_tag} on channel #{@id}!"
    end
  when AMQ::Protocol::Basic::CancelOk then
    @continuations.push(method)
    unregister_consumer(method.consumer_tag)
    delete_recorded_consumer(method.consumer_tag)
  when AMQ::Protocol::Tx::SelectOk, AMQ::Protocol::Tx::CommitOk, AMQ::Protocol::Tx::RollbackOk then
    @continuations.push(method)
  when AMQ::Protocol::Tx::SelectOk then
    @continuations.push(method)
  when AMQ::Protocol::Confirm::SelectOk then
    @continuations.push(method)
  when AMQ::Protocol::Basic::Ack then
    handle_ack_or_nack(method.delivery_tag, method.multiple, false)
  when AMQ::Protocol::Basic::Nack then
    handle_ack_or_nack(method.delivery_tag, method.multiple, true)
  when AMQ::Protocol::Channel::Close then
    closed!
    @connection.send_frame(AMQ::Protocol::Channel::CloseOk.encode(@id))

    # basic.ack, basic.reject, basic.nack. MK.
    if channel_level_exception_after_operation_that_has_no_response?(method)
      # Runs outside the reader loop so that the callback can perform
      # blocking operations such as channel.reopen.
      Thread.new { @on_error.call(self, method) } if @on_error
    else
      @last_channel_error = instantiate_channel_level_exception(method)
      @continuations.push(method)
    end

  when AMQ::Protocol::Channel::CloseOk then
    @continuations.push(method)
  else
    raise "Do not know how to handle #{method.inspect} in Bunny::Channel#handle_method"
  end
end

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

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

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Exchange parameters

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

Returns:

See Also:



473
474
475
# File 'lib/bunny/channel.rb', line 473

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

#inspectObject



2063
2064
2065
# File 'lib/bunny/channel.rb', line 2063

def inspect
  to_s
end

#jms_queue(name, opts = {}) ⇒ Bunny::Queue

Declares a Tanzu RabbitMQ JMS queue (a durable, replicated queue type). This queue type must be durable, non-exclusive, and non-auto-delete.

Parameters:

  • name (String)

    Queue name. Empty (server-generated) names are not supported by this method.

  • opts (Hash) (defaults to: {})

    Queue properties

Options Hash (opts):

  • :selector_fields (Array<String>) — default: nil

    Fields available for JMS selector expressions (e.g. ["priority", "region"], or ["*"] for all)

  • :selector_field_max_bytes (Integer) — default: nil

    Maximum byte size per selector field

  • :arguments (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

Raises:

  • (ArgumentError)

See Also:



616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/bunny/channel.rb', line 616

def jms_queue(name, opts = {})
  raise ArgumentError, "JMS queue name must not be nil" if name.nil?
  raise ArgumentError, "JMS queue name must not be empty" if name.empty?

  args = opts[:arguments] || {}
  args[Bunny::Queue::XArgs::SELECTOR_FIELDS]          = opts[:selector_fields]          if opts[:selector_fields]
  args[Bunny::Queue::XArgs::SELECTOR_FIELD_MAX_BYTES] = opts[:selector_field_max_bytes] if opts[:selector_field_max_bytes]

  final_opts = opts.merge(arguments: args)
  final_opts.delete(:selector_fields)
  final_opts.delete(:selector_field_max_bytes)

  durable_queue(name, Bunny::Queue::Types::JMS, final_opts)
end

#maybe_kill_consumer_work_pool!Object



2474
2475
2476
2477
2478
# File 'lib/bunny/channel.rb', line 2474

def maybe_kill_consumer_work_pool!
  if @work_pool && @work_pool.running?
    @work_pool.kill
  end
end

#maybe_pause_consumer_work_pool!Object



2469
2470
2471
# File 'lib/bunny/channel.rb', line 2469

def maybe_pause_consumer_work_pool!
  @work_pool.pause if @work_pool && @work_pool.running?
end

#maybe_reinitialize_consumer_pool!Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Used by the Automatic Network Failure Recovery feature.



2038
2039
2040
2041
2042
2043
# File 'lib/bunny/channel.rb', line 2038

def maybe_reinitialize_consumer_pool!
  unless @consumers.empty?
    @work_pool = ConsumerWorkPool.new(@work_pool.size, @work_pool.abort_on_exception)
    @work_pool.start
  end
end

#maybe_start_consumer_work_pool!Object

Starts consumer work pool. Lazily called by #basic_consume to avoid creating new threads that won't do any real work for channels that do not register consumers (e.g. only used for publishing). MK.



2462
2463
2464
2465
2466
# File 'lib/bunny/channel.rb', line 2462

def maybe_start_consumer_work_pool!
  if @work_pool && !@work_pool.running?
    @work_pool.start
  end
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.

Parameters:

  • delivery_tag (Integer)

    Delivery tag to reject

  • multiple (Boolean) (defaults to: false)

    (false) Should all unacknowledged messages up to this be rejected as well?

  • requeue (Boolean) (defaults to: false)

    (false) Should this message be requeued instead of dropping it?

See Also:



734
735
736
# File 'lib/bunny/channel.rb', line 734

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

#numberInteger

Returns Channel id.

Returns:

  • (Integer)

    Channel id



360
361
362
# File 'lib/bunny/channel.rb', line 360

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).



1941
1942
1943
# File 'lib/bunny/channel.rb', line 1941

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).



1949
1950
1951
# File 'lib/bunny/channel.rb', line 1949

def on_uncaught_exception(&block)
  @uncaught_exception_handler = block
end

#openBunny::Channel

Opens the channel and resets its internal state

Returns:



254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/bunny/channel.rb', line 254

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
  @frame_max = @connection.frame_max

  @status = :open

  self
end

#open?Boolean

Returns true if this channel is open, false otherwise.

Returns:

  • (Boolean)

    true if this channel is open, false otherwise



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

def open?
  @status == :open
end

#pending_server_named_queue_declaration?Boolean

Returns:

  • (Boolean)


2123
2124
2125
# File 'lib/bunny/channel.rb', line 2123

def pending_server_named_queue_declaration?
  @pending_queue_declare_name && @pending_queue_declare_name.empty?
end

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

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

Parameters:

  • name (String) (defaults to: AMQ::Protocol::EMPTY_STRING)

    Queue name. Pass an empty string to declare a server-named queue (make RabbitMQ generate a unique name).

  • opts (Hash) (defaults to: {})

    Queue properties and other options

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 (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

  • (Bunny::Queue)

    Queue that was declared or looked up in the cache

Raises:

  • (ArgumentError)

See Also:



521
522
523
524
525
526
527
528
# File 'lib/bunny/channel.rb', line 521

def queue(name = AMQ::Protocol::EMPTY_STRING, opts = {})
  raise ArgumentError, "queue name must not be nil" if name.nil?

  q = find_queue(name) || Bunny::Queue.new(self, name, opts)

  record_queue(q)
  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

Parameters:

  • name (String)

    Queue name

  • exchange (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

Returns:

  • (AMQ::Protocol::Queue::BindOk)

    RabbitMQ response

See Also:



1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
# File 'lib/bunny/channel.rb', line 1465

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

  exchange_name = exchange.is_a?(Bunny::Exchange) ? exchange.name : exchange
  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]

  result = self.queue_bind_without_recording_topology(name, exchange, opts)
  self.record_queue_binding_with(self, exchange_name, name, rk, args)

  result
end

#queue_bind_without_recording_topology(name, exchange, opts = {}) ⇒ Object

We need this bypassing topology version to avoid modifying the collections as we iterate over them during topology recovery.



1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
# File 'lib/bunny/channel.rb', line 1481

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

  exchange_name = exchange.is_a?(Bunny::Exchange) ? exchange.name : exchange

  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]
  @connection.send_frame(AMQ::Protocol::Queue::Bind.encode(@id,
    name,
    exchange_name,
    rk,
    false,
    args))

  with_continuation_timeout 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.

Parameters:

  • name (String)

    The name of the queue or an empty string to let RabbitMQ generate a name. Note that LF and CR characters will be stripped from the value.

  • opts (Hash) (defaults to: {})

    Queue properties

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.

  • :arguments (Hash) — default: {}

    Optional queue arguments (x-arguments)

Returns:

  • (AMQ::Protocol::Queue::DeclareOk)

    RabbitMQ response

See Also:



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

def queue_declare(name, opts = {})
  # strip trailing new line and carriage returns
  # just like RabbitMQ does
  safe_name = name.gsub(/[\r\n]/, "")
  is_server_named = (safe_name == AMQ::Protocol::EMPTY_STRING)
  passive = opts.fetch(:passive, false)
  durable = opts.fetch(:durable, false)
  exclusive = opts.fetch(:exclusive, false)
  auto_delete = opts.fetch(:auto_delete, false)
  args = opts[:arguments]

  result = self.queue_declare_without_recording_topology(name, opts)
  self.record_queue_with(self, result.queue, is_server_named, durable, exclusive, auto_delete, args) unless passive

  result
end

#queue_declare_without_recording_topology(name, opts = {}) ⇒ Object

We need this bypassing topology version to avoid modifying the collections as we iterate over them during topology recovery.



1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
# File 'lib/bunny/channel.rb', line 1363

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

  Bunny::Queue.verify_type!(opts[:arguments]) if opts[:arguments]

  # strip trailing new line and carriage returns
  # just like RabbitMQ does
  safe_name = name.gsub(/[\r\n]/, "")
  is_server_named = (safe_name == AMQ::Protocol::EMPTY_STRING)
  @pending_queue_declare_name = safe_name

  passive = opts.fetch(:passive, false)
  durable = opts.fetch(:durable, false)
  exclusive = opts.fetch(:exclusive, false)
  auto_delete = opts.fetch(:auto_delete, false)
  args = opts[:arguments]

  @connection.send_frame(
    AMQ::Protocol::Queue::Declare.encode(@id,
      @pending_queue_declare_name,
      passive,
      durable,
      exclusive,
      auto_delete,
      false,
      args))

  begin
    with_continuation_timeout do
      @last_queue_declare_ok = wait_on_continuations
    end
  ensure
    # clear pending continuation context if it belongs to us
    @pending_queue_declare_name = nil if @pending_queue_declare_name == safe_name
  end
  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

Parameters:

  • name (String)

    Queue name

  • opts (Hash) (defaults to: {})

    Options

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?

Returns:

  • (AMQ::Protocol::Queue::DeleteOk)

    RabbitMQ response

See Also:



1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
# File 'lib/bunny/channel.rb', line 1414

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))
  with_continuation_timeout do
    @last_queue_delete_ok = wait_on_continuations
  end
  raise_if_continuation_resulted_in_a_channel_error!
  self.delete_recorded_queue_named(name)
  self.deregister_queue_named(name)

  @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.

Parameters:

  • name (String)

    Queue name

Returns:

  • (AMQ::Protocol::Queue::PurgeOk)

    RabbitMQ response

See Also:



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
# File 'lib/bunny/channel.rb', line 1439

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

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

  with_continuation_timeout 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

Parameters:

  • name (String)

    Queue name

  • exchange (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • routing_key (String) — default: nil

    Routing key used for binding

  • arguments (Hash) — default: {}

    Optional arguments

Returns:

  • (AMQ::Protocol::Queue::UnbindOk)

    RabbitMQ response

See Also:



1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
# File 'lib/bunny/channel.rb', line 1518

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

  exchange_name = exchange.is_a?(Bunny::Exchange) ? exchange.name : exchange

  rk = (opts[:routing_key] || opts[:key])
  args = opts[:arguments]
  @connection.send_frame(AMQ::Protocol::Queue::Unbind.encode(@id,
      name,
      exchange_name,
      rk,
      args))
  with_continuation_timeout do
    @last_queue_unbind_ok = wait_on_continuations
  end

  raise_if_continuation_resulted_in_a_channel_error!
  self.delete_recorded_queue_binding(self, exchange_name, name, rk, args)

  @last_queue_unbind_ok
end

#quorum_queue(name, opts = {}) ⇒ Bunny::Queue

Declares a new client-named quorum queue.

Parameters:

  • name (String)

    Queue name. Empty (server-generated) names are not supported by this method.

  • opts (Hash) (defaults to: {})

    Queue properties and other options. Durability, exclusivity, auto-deletion options will be ignored.

Options Hash (opts):

  • :arguments (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

Raises:

  • (ArgumentError)

See Also:



541
542
543
544
545
546
# File 'lib/bunny/channel.rb', line 541

def quorum_queue(name, opts = {})
  raise ArgumentError, "quorum queue name must not be nil" if name.nil?
  raise ArgumentError, "quorum queue name must not be empty (server-named QQs do not make sense)" if name.empty?

  durable_queue(name, Bunny::Queue::Types::QUORUM, opts)
end

#read_and_reset_only_acks_receivedObject



2391
2392
2393
2394
2395
2396
2397
# File 'lib/bunny/channel.rb', line 2391

def read_and_reset_only_acks_received
  @unconfirmed_set_mutex.synchronize do
    result = @only_acks_received
    @only_acks_received = true
    result
  end
end

#read_next_frame(options = {}) ⇒ Object



2481
2482
2483
# File 'lib/bunny/channel.rb', line 2481

def read_next_frame(options = {})
  @connection.read_next_frame(options = {})
end

#record_consumer_with(ch, consumer_tag, queue_name, callable, manual_ack, exclusive, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • consumer_tag (String)
  • queue_name (String)
  • callable (#call)
  • manual_ack (Boolean)
  • exclusive (Boolean)
  • arguments (Hash)


2638
2639
2640
# File 'lib/bunny/channel.rb', line 2638

def record_consumer_with(ch, consumer_tag, queue_name, callable, manual_ack, exclusive, arguments)
  @connection.record_consumer_with(ch, consumer_tag, queue_name, callable, manual_ack, exclusive, arguments)
end

#record_exchange(exchange) ⇒ Object

Parameters:



2564
2565
2566
# File 'lib/bunny/channel.rb', line 2564

def record_exchange(exchange)
  @connection.record_exchange(exchange)
end

#record_exchange_binding_with(ch, source_name, destination_name, routing_key, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • source_name (String)
  • destination_name (String)
  • routing_key (String)
  • arguments (Hash)


2616
2617
2618
# File 'lib/bunny/channel.rb', line 2616

def record_exchange_binding_with(ch, source_name, destination_name, routing_key, arguments)
  @connection.record_exchange_binding_with(ch, source_name, destination_name, routing_key, arguments)
end

#record_exchange_with(ch, name, type, durable, auto_delete, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • name (String)
  • type (String)
  • durable (Boolean)
  • auto_delete (Boolean)
  • arguments (Hash)


2574
2575
2576
# File 'lib/bunny/channel.rb', line 2574

def record_exchange_with(ch, name, type, durable, auto_delete, arguments)
  @connection.record_exchange_with(ch, name, type, durable, auto_delete, arguments)
end

#record_queue(queue) ⇒ Object

Parameters:



2517
2518
2519
# File 'lib/bunny/channel.rb', line 2517

def record_queue(queue)
  @connection.record_queue(queue)
end

#record_queue_binding_with(ch, exchange_name, queue_name, routing_key, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • exchange_name (String)
  • queue_name (String)
  • routing_key (String)
  • arguments (Hash)


2596
2597
2598
# File 'lib/bunny/channel.rb', line 2596

def record_queue_binding_with(ch, exchange_name, queue_name, routing_key, arguments)
  @connection.record_queue_binding_with(ch, exchange_name, queue_name, routing_key, arguments)
end

#record_queue_name_change(old_name, new_name) ⇒ Object

Used by the Automatic Network Failure Recovery feature.

Parameters:

  • old_name (String)
  • new_name (String)


2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
# File 'lib/bunny/channel.rb', line 2024

def record_queue_name_change(old_name, new_name)
  @queue_mutex.synchronize do
    if (orig = @queues[old_name])
      @queues.delete(old_name)

      orig.update_name_to(new_name)
      @queues[new_name] = orig.dup
    end
  end
end

#record_queue_with(ch, name, server_named, durable, auto_delete, exclusive, arguments) ⇒ Object

Parameters:

  • ch (Bunny::Channel)
  • name (String)
  • server_named (Boolean)
  • durable (Boolean)
  • auto_delete (Boolean)
  • exclusive (Boolean)
  • arguments (Hash)


2528
2529
2530
# File 'lib/bunny/channel.rb', line 2528

def record_queue_with(ch, name, server_named, durable, auto_delete, exclusive, arguments)
  @connection.record_queue_with(ch, name, server_named, durable, auto_delete, exclusive, arguments)
end

#recover(ignored = true) ⇒ Object

Tells RabbitMQ to redeliver unacknowledged messages



688
689
690
691
# File 'lib/bunny/channel.rb', line 688

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

#recover_cancelled_consumers!Object



2046
2047
2048
# File 'lib/bunny/channel.rb', line 2046

def recover_cancelled_consumers!
  @recover_cancelled_consumers = true
end

#recover_confirm_modeObject

Recovers publisher confirms mode. Used by the Automatic Network Failure Recovery feature. Set the offset to the previous publish sequence index as the protocol will reset the index to after recovery.



1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
# File 'lib/bunny/channel.rb', line 1987

def recover_confirm_mode
  return unless using_publisher_confirmations?

  @unconfirmed_set_mutex.synchronize do
    @unconfirmed_set.clear
    @delivery_tag_offset = @next_publish_seq_no - 1

    if @confirms_tracking_enabled
      @per_message_continuations_mutex.synchronize do
        @per_message_continuations.each_value { |c| c.push(:network_error) }
        @per_message_continuations.clear
      end
    end

    @outstanding_limit_cond&.broadcast
  end

  confirm_select(@confirms_callback,
                 tracking: @confirms_tracking_enabled,
                 outstanding_limit: @outstanding_limit,
                 confirm_timeout: @confirm_timeout)
end

#recover_from_network_failureObject

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



1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
# File 'lib/bunny/channel.rb', line 1963

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

  # Topology is now recovered by [Bunny::Session] via the data in [Bunny::TopologyRegistry].
end

#recover_prefetch_settingObject

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



1978
1979
1980
# File 'lib/bunny/channel.rb', line 1978

def recover_prefetch_setting
  basic_qos(@prefetch_count, @prefetch_global) if @prefetch_count
end

#recover_tx_modeObject

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



2014
2015
2016
# File 'lib/bunny/channel.rb', line 2014

def recover_tx_mode
  tx_select if @tx_mode
end

#recovering!Object



346
347
348
# File 'lib/bunny/channel.rb', line 346

def recovering!
  @status = :recovering
end

#recovers_cancelled_consumers?Boolean

Returns:

  • (Boolean)


2051
2052
2053
# File 'lib/bunny/channel.rb', line 2051

def recovers_cancelled_consumers?
  !!@recover_cancelled_consumers
end

#recovery_completed!Object



351
352
353
# File 'lib/bunny/channel.rb', line 351

def recovery_completed!
  @status = :open
end

#register_consumer(consumer_tag, consumer) ⇒ Object



2078
2079
2080
2081
2082
2083
2084
2085
# File 'lib/bunny/channel.rb', line 2078

def register_consumer(consumer_tag, consumer)
  @consumer_mutex.synchronize do
    @consumers[consumer_tag] = consumer
    if @last_consumer_tag == consumer_tag
      @last_consumer = consumer
    end
  end
end

#register_exchange(exchange) ⇒ Object

Parameters:



2546
2547
2548
# File 'lib/bunny/channel.rb', line 2546

def register_exchange(exchange)
  @exchange_mutex.synchronize { @exchanges[exchange.name] = exchange }
end

#register_queue(queue) ⇒ Object

Parameters:



2499
2500
2501
# File 'lib/bunny/channel.rb', line 2499

def register_queue(queue)
  @queue_mutex.synchronize { @queues[queue.name] = queue }
end

#reject(delivery_tag, requeue = false) ⇒ Object

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

Parameters:

  • delivery_tag (Integer)

    Delivery tag to reject

  • requeue (Boolean) (defaults to: false)

    Should this message be requeued instead of dropping it?

See Also:



708
709
710
# File 'lib/bunny/channel.rb', line 708

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

#release_all_continuationsObject



2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
# File 'lib/bunny/channel.rb', line 2446

def release_all_continuations
  @threads_waiting_on_confirms_continuations.each(&:run)
  @threads_waiting_on_continuations.each(&:run)
  @threads_waiting_on_basic_get_continuations.each(&:run)

  if @outstanding_limit_cond
    @unconfirmed_set_mutex.synchronize { @outstanding_limit_cond.broadcast }
  end

  reset_continuations
end

#reopenBunny::Channel

Reopens a channel that was closed by the server (e.g. due to a consumer delivery acknowledgement timeout). The channel is reopened on the same connection, reusing its original channel id, and its prefetch, confirm, and transactional settings are recovered.

This does NOT recover topology (queues, exchanges, bindings, consumers). Use Session#recover_channel_topology for that.

Returns:

See Also:



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/bunny/channel.rb', line 310

def reopen
  raise "Cannot reopen a channel that is not closed" unless closed?

  existing = @connection.synchronised_find_channel(@id)
  if existing && existing != self
    raise "Channel id #{@id} has been reassigned to another channel"
  end

  @work_pool = ConsumerWorkPool.new(@work_pool.size, @work_pool.abort_on_exception)
  @work_pool.start

  open

  recover_from_network_failure

  self
end

#stream(name, opts = {}) ⇒ Bunny::Queue

Declares a new client-named stream (that Bunny can use as if it was a queue). Note that Bunny would still use AMQP 0-9-1 to perform operations on this "queue". To use stream-specific operations and to gain from stream protocol efficiency and partitioning, use a Ruby client for the RabbitMQ stream protocol.

Parameters:

  • name (String)

    Stream name. Empty (server-generated) names are not supported by this method.

  • opts (Hash) (defaults to: {})

    Queue properties and other options. Durability, exclusivity, auto-deletion options will be ignored.

Options Hash (opts):

  • :arguments (Hash) — default: {}

    Optional arguments (x-arguments)

Returns:

Raises:

  • (ArgumentError)

See Also:



563
564
565
566
567
568
# File 'lib/bunny/channel.rb', line 563

def stream(name, opts = {})
  raise ArgumentError, "stream name must not be nil" if name.nil?
  raise ArgumentError, "stream name must not be empty (server-named QQs do not make sense)" if name.empty?

  durable_queue(name, Bunny::Queue::Types::STREAM, opts)
end

#synchronize(&block) ⇒ Object

Synchronizes given block using this channel's mutex.



1917
1918
1919
# File 'lib/bunny/channel.rb', line 1917

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

#temporary_queue(opts = {}) ⇒ Bunny::Queue

Declares a new server-named queue that is automatically deleted when the connection is closed.

Returns:

See Also:



665
666
667
668
669
670
# File 'lib/bunny/channel.rb', line 665

def temporary_queue(opts = {})
  temporary_queue_opts = {
    exclusive: true
  }
  queue("", opts.merge(temporary_queue_opts))
end

#to_sString

Returns Brief human-readable representation of the channel.

Returns:

  • (String)

    Brief human-readable representation of the channel



2059
2060
2061
# File 'lib/bunny/channel.rb', line 2059

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

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

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

Parameters:

  • name (String)

    Exchange name

  • opts (Hash) (defaults to: {})

    Exchange parameters

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)

Returns:

See Also:



455
456
457
# File 'lib/bunny/channel.rb', line 455

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

#tx_commitAMQ::Protocol::Tx::CommitOk

Commits current transaction

Returns:

  • (AMQ::Protocol::Tx::CommitOk)

    RabbitMQ response



1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
# File 'lib/bunny/channel.rb', line 1800

def tx_commit
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Commit.encode(@id))
  with_continuation_timeout 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

Returns:

  • (AMQ::Protocol::Tx::RollbackOk)

    RabbitMQ response



1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
# File 'lib/bunny/channel.rb', line 1815

def tx_rollback
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Rollback.encode(@id))
  with_continuation_timeout 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)

Returns:

  • (AMQ::Protocol::Tx::SelectOk)

    RabbitMQ response



1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# File 'lib/bunny/channel.rb', line 1784

def tx_select
  raise_if_no_longer_open!

  @connection.send_frame(AMQ::Protocol::Tx::Select.encode(@id))
  with_continuation_timeout 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

#unregister_consumer(consumer_tag) ⇒ Object



2088
2089
2090
2091
2092
2093
2094
2095
2096
# File 'lib/bunny/channel.rb', line 2088

def unregister_consumer(consumer_tag)
  @consumer_mutex.synchronize do
    @consumers.delete(consumer_tag)
    if @last_consumer_tag == consumer_tag
      @last_consumer_tag = nil
      @last_consumer = nil
    end
  end
end

#using_publisher_confirmations?Boolean Also known as: using_publisher_confirms?

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

Returns:

  • (Boolean)

    true if this channel has Publisher Confirms enabled, false otherwise



1840
1841
1842
# File 'lib/bunny/channel.rb', line 1840

def using_publisher_confirmations?
  @next_publish_seq_no > 0
end

#using_tx?Boolean

Returns true if this channel has transactions enabled.

Returns:

  • (Boolean)

    true if this channel has transactions enabled



1828
1829
1830
# File 'lib/bunny/channel.rb', line 1828

def using_tx?
  !!@tx_mode
end

#wait_for_confirmsBoolean

Blocks calling thread until confirms are received for all currently unacknowledged published messages. Returns immediately if there are no outstanding confirms.

Returns:

  • (Boolean)

    true if all messages were acknowledged positively since the last time this method was called, false otherwise

See Also:



1905
1906
1907
1908
# File 'lib/bunny/channel.rb', line 1905

def wait_for_confirms
  wait_on_confirms_continuations
  read_and_reset_only_acks_received
end

#wait_for_outstanding_slot_lockedObject

Waits for a slot when outstanding limit is reached. Assumes @unconfirmed_set_mutex is already held.



2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
# File 'lib/bunny/channel.rb', line 2402

def wait_for_outstanding_slot_locked
  limit = @outstanding_limit
  return if @unconfirmed_set.size < limit

  timeout_sec = (@confirm_timeout || @connection.continuation_timeout) / 1000.0
  deadline = Bunny::Timestamp.monotonic + timeout_sec

  while @unconfirmed_set.size >= limit
    raise_if_no_longer_open!

    remaining = deadline - Bunny::Timestamp.monotonic
    raise Timeout::Error, "Timed out waiting for publisher confirms (limit: #{limit})" if remaining <= 0

    @outstanding_limit_cond.wait(remaining)
  end
end

#wait_for_publish_confirm(seq_no, continuation) ⇒ Object



2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
# File 'lib/bunny/channel.rb', line 2420

def wait_for_publish_confirm(seq_no, continuation)
  t = Thread.current
  @threads_waiting_on_confirms_continuations << t

  begin
    timeout = @confirm_timeout || @connection.continuation_timeout
    case continuation.poll(timeout)
    when :ack, true
      # confirmed
    when :nack
      raise MessageNacked.new("Message #{seq_no} was nacked", seq_no)
    when :network_error
      raise NetworkFailure.new("Network failure waiting for confirm", nil)
    when nil
      raise Timeout::Error, "Timed out waiting for publisher confirm"
    end
  ensure
    @threads_waiting_on_confirms_continuations.delete(t)
    @per_message_continuations_mutex.synchronize do
      @per_message_continuations.delete(seq_no)
    end
  end
end

#wait_on_basic_get_continuationsObject



2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
# File 'lib/bunny/channel.rb', line 2350

def wait_on_basic_get_continuations
  if @connection.threaded
    t = Thread.current
    @threads_waiting_on_basic_get_continuations << t

    begin
      @basic_get_continuations.poll(@connection.continuation_timeout)
    ensure
      @threads_waiting_on_basic_get_continuations.delete(t)
    end
  else
    connection.reader_loop.run_once until @basic_get_continuations.length > 0

    @basic_get_continuations.pop
  end
end

#wait_on_confirms_continuationsObject



2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
# File 'lib/bunny/channel.rb', line 2368

def wait_on_confirms_continuations
  raise_if_no_longer_open!

  if @connection.threaded
    t = Thread.current
    @threads_waiting_on_confirms_continuations << t

    begin
      while @unconfirmed_set_mutex.synchronize { !@unconfirmed_set.empty? }
        @confirms_continuations.poll(@connection.continuation_timeout)
      end
    ensure
      @threads_waiting_on_confirms_continuations.delete(t)
    end
  else
    unless @unconfirmed_set.empty?
      connection.reader_loop.run_once until @confirms_continuations.length > 0
      @confirms_continuations.pop
    end
  end
end

#wait_on_continuationsObject



2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
# File 'lib/bunny/channel.rb', line 2332

def wait_on_continuations
  if @connection.threaded
    t = Thread.current
    @threads_waiting_on_continuations << t

    begin
      @continuations.poll(@connection.continuation_timeout)
    ensure
      @threads_waiting_on_continuations.delete(t)
    end
  else
    connection.reader_loop.run_once until @continuations.length > 0

    @continuations.pop
  end
end

#wait_on_continuations_timeoutObject



247
248
249
# File 'lib/bunny/channel.rb', line 247

def wait_on_continuations_timeout
  @connection.transport_write_timeout
end

#with_continuation_timeout(&block) ⇒ Object



2073
2074
2075
# File 'lib/bunny/channel.rb', line 2073

def with_continuation_timeout(&block)
  Bunny::Timeout.timeout(wait_on_continuations_timeout, ClientTimeout, &block)
end