最近,我的任务是构建REST请求,该请求负责向Kafka的入站通道发送消息,然后等待出站通道的输出。一切都进行得很顺利,直到我遇到了与等待这个特定消息有关的问题。
值得指出的是,在成功到达之后,消息会被写入全局消息持有者,这只是一个隐藏在幕后的红宝石哈希。下面是监视哈希的函数,直到哈希填充了一些值。
def monitor_payment_hash(key)
while @uuid.payment_create.get_message(key).nil?
next
end
@uuid.payment_create.get_message(key)
end
以这种方式实施它是否合适?在这一点上我应该做些什么呢?
注意: Kafka消费者在一个单独的线程中运行。
更新
我刚去看了一下红宝石博士,偶然发现了一些有趣的频道。据我所知,渠道是在rubytines之间进行交流的最佳选择(这只是goroutines的一个奇特的名称,但在ruby生态系统:)
发布于 2021-04-24 17:14:47
我认为您需要timeout
和一种强制停止轮询过程的方法,而且,您将来可能需要改进抽象。
class Poller
def self.poll(key:, from_source:, options: {})
start_time = Time.now
catch(:stop_polling) do
loop do
message = from_source.get_message(key)
if message.nil?
wait_time = Time.now - start_time
throw :stop_polling if wait_time > options[:timeout]
else
yield(message) if block_given?
throw :stop_polling
end
end
end
end
end
def monitor_payment_hash(key)
Poller.poll key: key, from_source: @uuid.payment_create, options: {timeout: 60} do |message|
# write to the global message holders
# or handle message by block
yield(message) if block_given?
end
end
您可能需要添加更多的逻辑,例如重试如果超时,轮询一个键列表,日志.我建议您学习如何从这个源构建一个长轮询:https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-sqs/lib/aws-sdk-sqs/queue_poller.rb
https://stackoverflow.com/questions/67240896
复制相似问题