开发者

Rails: Is it possible to initialize some stuff in a thread?

开发者 https://www.devze.com 2023-02-19 00:06 出处:网络
In one of the my initializer I need to fetch some hashes from a redis instance. However due to the number of hashs and the connection weaknesses the loading can take quite a moment.

In one of the my initializer I need to fetch some hashes from a redis instance. However due to the number of hashs and the connection weaknesses the loading can take quite a moment. Since it's in the initializer, the application is not available until the hashes have all been loaded.

Therefore I was thinking I could perform the initialization in a thread so the application can start and then the hashes would get loaded on their on time as they are not essential to the application.

I have tried something like this:

REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
STORE = {}
Thread.abort_on_exception = true
Thread.new do
  REDIS.keys.each do |key|
    STORE[key] = REDIS[key]
  end
end

But it does not work and there are no error messages :(

Any ideas?开发者_Python百科

Alex


Will you please explain a bit more?

  • What is the goal here? What are you doing with the contents of the hashes?
  • What stack are you running?

I tried a simple test against Rails 3.0.5/WEBrick running on my local machine (OS X 10.6.7):

puts "I am in the main thread."
Thread.abort_on_exception = true
Thread.new do
  for i in 1..5
    puts "I am in a thread."
    sleep 2
  end
end
Thread.new do
  for i in 1..5
    puts "I am in another thread."
    sleep 1
  end
end

And it worked the way I expected:

ultramarine:ThreadTest jdc$ rails s
=> Booting WEBrick
=> Rails 3.0.5 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
I am in the main thread.
I am in a thread.
I am in another thread.
[2011-03-23 18:30:28] INFO  WEBrick 1.3.1
[2011-03-23 18:30:28] INFO  ruby 1.9.2 (2010-12-25) [x86_64-darwin10.5.0]
[2011-03-23 18:30:28] INFO  WEBrick::HTTPServer#start: pid=5802 port=3000
I am in another thread.
I am in a thread.
I am in another thread.
I am in another thread.
I am in a thread.
I am in another thread.
I am in a thread.
I am in a thread.
0

精彩评论

暂无评论...
验证码 换一张
取 消