-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpublishing.rb
60 lines (45 loc) · 1.56 KB
/
publishing.rb
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
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true
require "rabbit/publishing/message"
module Rabbit
module Publishing
autoload :Job, "rabbit/publishing/job"
autoload :ChannelsPool, "rabbit/publishing/channels_pool"
extend self
MUTEX = Mutex.new
def publish(msg)
return if Rabbit.config.skip_publish?
pool.with_channel msg.confirm_select? do |ch|
ch.basic_publish *msg.basic_publish_args
raise MessageNotDelivered, "RabbitMQ message not delivered: #{msg}" \
if msg.confirm_select? && !ch.wait_for_confirms
log msg
end
rescue Timeout::Error
raise MessageNotDelivered, <<~MESSAGE
Timeout while sending message #{msg}. Possible reasons:
- #{msg.real_exchange_name} exchange is not found
- RabbitMQ is extremely high loaded
MESSAGE
end
def pool
MUTEX.synchronize { @pool ||= ChannelsPool.new(create_client) }
end
private
def create_queue_if_not_exists(channel, message)
channel.queue(message.routing_key, durable: true)
end
def create_client
config = Rails.application.config_for("sneakers") rescue {}
config = config["bunny_options"].to_h.symbolize_keys
Bunny.new(config).start
end
def log(message)
@logger ||= Rabbit.config.publish_logger
metadata = [
message.real_exchange_name, message.routing_key, JSON.dump(message.headers),
message.event, message.confirm_select? ? "confirm" : "no-confirm"
]
@logger.debug "#{metadata.join ' / '}: #{JSON.dump(message.data)}"
end
end
end