Lee*_*Lee 9 ruby ruby-on-rails
根据这个答案,他们是,但随后海报说JRuby中的事情有所不同,所以我很困惑?
我正在使用类实例变量实现多租户解决方案,因此我使用的Ruby实现或Web服务器无关紧要,我需要确保数据不会被泄露.
这是我的代码:
class Tenant < ActiveRecord::Base
def self.current_tenant=(tenant)
@tenant = tenant
end
def self.current_tenant
@tenant
end
end
Run Code Online (Sandbox Code Playgroud)
我需要做些什么才能确保无论发生什么(更改Ruby实现,更改Web服务器,新的Ruby线程功能等),我的代码都是线程安全的?
Uri*_*ssi 14
由于租期属性的范围是请求,我建议您将其保留在当前线程的范围内.由于请求是在一个线程上处理的,并且一个线程一次处理一个请求 - 只要您始终在请求开始时设置租期就可以了(为了额外的安全性,您可能希望取消 - 在请求结束时分配租户).
为此,您可以使用线程本地属性:
class Tenant < ActiveRecord::Base
def self.current_tenant=(tenant)
Thread.current[:current_tenant] = tenant
end
def self.current_tenant
Thread.current[:current_tenant]
end
def self.clear_current_tenant
Thread.current[:current_tenant] = nil
end
end
Run Code Online (Sandbox Code Playgroud)
由于这是使用线程存储,因此您完全是线程安全的 - 每个线程负责自己的数据.