在 ruby 或 jruby 中处理线程
我有一个rabbitmq队列订阅者,每次使用新消息时都会启动一个新线程:
AMQP.start(@conf) do |connection|
channel = AMQP::Channel.new(connection)
requests_queue = channel.queue("one")
requests_queue.subscribe(:ack => true) do |header, body|
puts "we have a message at #{Time.now} and n is #{n}"
url_search = MultiJson.decode(body)
Thread.new do
5.times do
lead = get_lead(n, (n == 5))
puts "message #{n} is_last = #{lead.is_last} at #{Time.now}";
AMQP::Exchange.default.publish(
MultiJson.encode(lead),
:routing_key => header.reply_to,
:correlation_id => header.correlation_id
)
n += 1
sleep(2)
end
end
end
end
我的问题是,处理消息后如何处置该线程?我应该使用线程池吗?
我正在使用 JRuby。上面的代码是否使用普通的 ruby 语法在幕后创建 Java JVM 线程,或者我应该显式创建 Java 线程?
I have a rabbitmq queue subscriber that spins up a new thread every time a new message is consumed:
AMQP.start(@conf) do |connection|
channel = AMQP::Channel.new(connection)
requests_queue = channel.queue("one")
requests_queue.subscribe(:ack => true) do |header, body|
puts "we have a message at #{Time.now} and n is #{n}"
url_search = MultiJson.decode(body)
Thread.new do
5.times do
lead = get_lead(n, (n == 5))
puts "message #{n} is_last = #{lead.is_last} at #{Time.now}";
AMQP::Exchange.default.publish(
MultiJson.encode(lead),
:routing_key => header.reply_to,
:correlation_id => header.correlation_id
)
n += 1
sleep(2)
end
end
end
end
My question is, how do I dispose of the thread after the message is handled? Should I be using the threadpool?
I am using JRuby. Does the above code create a Java JVM thread behind the scenes using the normal ruby syntax or should I be explicitly creating a Java thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你不必手动处理线程,你应该使用 ruby 线程,据我所知,它们是 jruby 中的 java 线程,这是 jruby 获得良好性能的原因。
如果您想在下一步之前确保所有线程都已完成,常见的做法是启动几个线程,然后在继续之前连接所有线程,但这里似乎不需要这样做。
这是一个小测试程序:
正如您所看到的,生成的后台线程被自动删除。 (在 jruby 以及 1.9.2 中测试
You don't have to manually dispose the thread I think, and you should be using ruby threads, from what I gather they are java threads in jruby, which is from what jruby gets it's nice performance.
A common thing to do is to spin up a couple of threads and then join all of them before continuing if you want to be sure that all are complete before the next step, but it doesn't seem to be required here.
Here's a little test program:
As you can see the spawned background thread is automatically removed. (Tested in jruby as well as 1.9.2