简体   繁体   English

如何从Puma获取隔离的线程信息

[英]How to get isolated thread information from Puma

I have a Rails application using Puma. 我有一个使用Puma的Rails应用程序。

The Puma configuration is: Puma配置为:

workers 2
threads 1, 16
app_dir = File.expand_path("../..", __FILE__)
tmp_dir = "#{app_dir}/tmp"
rails_env = ENV['RAILS_ENV'] || "development"
environment rails_env
daemonize
bind "unix://#{tmp_dir}/sockets/puma.sock"
stdout_redirect "log/puma.stdout.log", "log/puma.stderr.log", true
pidfile "#{tmp_dir}/pids/puma.pid"
state_path "#{tmp_dir}/pids/puma.state"

When two requests have one pid, they have a common state. 当两个请求具有一个pid时,它们将具有一个公共状态。

For example, we have a simple singleton: 例如,我们有一个简单的单例:

class Test
  include Singleton
  attr_accessor :field
end

The first request sets: 第一个请求集:

Test.instance.field = 'from_first_request'

In the second request we see: 在第二个请求中,我们看到:

puts(Test.instance.field) # => 'from_first_request'

Is this the correct behaviour? 这是正确的行为吗? Can we get the isolated state for any requests on one pid? 我们可以在一个pid上获取任何请求的隔离状态吗?

If you use Rails 5.0 you can also use new thread specific variable, like this: 如果使用Rails 5.0,则还可以使用新的线程特定变量,如下所示:

class SomeSingleton
  thread_mattr_accessor :field
end

If your Rails version < 5.0 you're still able to store field in Thread.current, like this: 如果您的Rails版本<5.0,您仍然可以在Thread.current中存储字段,如下所示:

class SomeSingleton
  def self.field=(field)
    Thread.current[:field] = field
  end

  def self.field
    Thread.current[:field]
  end
end

Let me know if it helped. 让我知道是否有帮助。

您也可以使用request_store gem。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM