File: high_and_low_priority.rb

package info (click to toggle)
ruby-bunny 2.23.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,644 kB
  • sloc: ruby: 10,256; sh: 70; makefile: 8
file content (50 lines) | stat: -rw-r--r-- 1,126 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env ruby
# encoding: utf-8

require "bundler"
Bundler.setup

$:.unshift(File.expand_path("../../../lib", __FILE__))

require 'bunny'

HIGH_PRIORITY_Q = "bunny.examples.priority.hilo.high"
LOW_PRIORITY_Q  = "bunny.examples.priority.hilo.low"

conn = Bunny.new(heartbeat_timeout: 8)
conn.start

ch1  = conn.create_channel
ch2  = conn.create_channel
hi_q = ch1.queue(HIGH_PRIORITY_Q, :durable => false)
lo_q = ch2.queue(LOW_PRIORITY_Q,  :durable => false)

ch3  = conn.create_channel
x    = ch3.default_exchange

# create a backlog of low priority messages
30.times do
  x.publish(rand.to_s, :routing_key => LOW_PRIORITY_Q)
end

# and a much smaller one of high priority messages
3.times do
  x.publish(rand.to_s, :routing_key => HIGH_PRIORITY_Q)
end

hi_q.subscribe do |delivery_info, metadata, payload|
  puts "[high] Consumed #{payload}"
end

lo_q.subscribe do |delivery_info, metadata, payload|
  puts "[low] Consumed #{payload}"
end

loop do
  sleep 0.5
  data = rand.to_s
  rk   = [HIGH_PRIORITY_Q, LOW_PRIORITY_Q].sample

  x.publish(data, :routing_key => rk)
  puts "Published #{data}, routing key: #{rk}"
end