【Rails App】 应用服务器从Passenger切换为Puma, Grape出现线程安全问题

时间:2023-03-10 05:08:07
【Rails App】 应用服务器从Passenger切换为Puma, Grape出现线程安全问题

Grape中的代码如下:

def market
@market ||= Market.find(params[:id])
end

@market基于类层次的实例变量,属于非线程安全,如果一直使用多线程服务器,可以使用 Thread.current 代替:

def market
Thread.current[:market] ||= Market.find(params[:id])
end

如果考虑到以后哦使用其他类型服务器,比如 Thin, 可以使用 request_store gem 包,参考: https://github.com/steveklabnik/request_store

参考:

https://github.com/ruby-grape/grape-rabl/issues/37

https://ruby-china.org/topics/30188

https://*.com/questions/9558192/thread-safety-class-variables-in-ruby