独角兽工人之间如何共享 Rails 会话?
我使用 unicorn 作为 rails 服务器,我已经为它配置了 5 个 worker.
I am using unicorn as rails server, I have configured five workers for it.
我不确定这是否会影响用户会话,所以我做了一个小实验:
I was not sure if this would affect user session, so I did a little experiment:
puts "------"
puts session[:session_id]
puts "session obj: #{session.hash}"
puts "pid: #{Process.pid}"
这是结果
------
69db720b6620288416ae4ba6f921dfb8
session obj: -4054823339922854099
pid: 4396
------
69db720b6620288416ae4ba6f921dfb8
session obj: 4220002746750993661
pid: 4527
------
69db720b6620288416ae4ba6f921dfb8
session obj: 2637320844486598221
pid: 4396
会话 ID 始终相同
会话对象每次都不一样
第一个和第三个请求的pid是一样的
The pids for the first and third requests are the same
所以我假设 rails 会话内容(不是单例对象,因为每个工作人员都有自己的进程,所以不能这样做)在同一个主人下的不同独角兽工作人员之间共享,但这是否在任何地方都有记录?
So I assume that rails session content(not singleton object, which can not be since each worker has its own process) is shared between different unicorn workers under the same master, but is this documented anywhere?
而且是由rails框架实现的吗?还是 unicorn_rails 这样做?
And is it implemented by the rails framework? or is unicorn_rails doing this?
这部分取决于所使用的会话存储.默认是 cookie 存储,其中整个数据被序列化并存储在会话 cookie 中.其他商店只是在会话 cookie 中存储一个 id 并从其他来源(例如 redis)获取数据
This partly depends on the session store used. The default is the cookie store where the entire data is serialized and stored inside the session cookie. Other stores just store an id in the session cookie and fetch the data from some other source (eg redis)
虽然 session
看起来像 Hash
的一个实例,但它不是 - 它是 Request::Session
的一个实例,它包含了很多其他的东西(例如当前请求的详细信息)所以 session.hash
每次都不同是正常的.
While session
looks like an instance of Hash
it's not - it's an instance of Request::Session
which contains a bunch of other things (such as the details of the current request) so it's normal for session.hash
to be different each time.
您可以使用 session.to_hash
将会话转换为实际的哈希值,尽管如此您可能会发现 session.to_hash.hash
因哈希值而因进程而异不能保证跨进程相同(特别是,对于字符串,它们依赖于进程)
You can turn the session into an actual hash with session.to_hash
, although even then you will probably find that session.to_hash.hash
differs across processes since hash values are not guaranteed to be the same across processes (in particular, for strings they are process dependant)