这是我的第一个 Sinatra 项目,我已经很晚了,我意识到当使用 ActiveRecord 一次发出多个请求时,我遇到了问题。如果我只提出一个请求,那么每个请求都会独立工作。但是当我同时调用两者时,我会失败。
到目前为止,我已经将问题范围缩小到同时存在两个 ActiveRecord 请求的问题。也许我没有正确设置 ActiveRecord?我使用 PostgreSQL 是因为 Heroku 使用它,并且不想改变。 (这个问题也发生在 Heroku 上。)
这是日志:
192.168.1.113 - - [30/Sep/2012:10:33:00 MDT] "GET /version/current?platform=android HTTP/1.1" 200 33
- -> /version/current?platform=android ActiveRecord::StatementInvalid - NoMethodError: undefined method `fields' for nil:NilClass: SELECT "rankings".* FROM "rankings" WHERE "rankings"."user_id" = 1 LIMIT 1:
/Users/zablanc/.rvm/gems/ruby-1.9.3-head@emm/gems/activerecord-3.2.7/lib/active_record/connection_adapters/postgresql_adapter.rb:667:in `block in exec_query'
...
Warning! Rack::Session::Cookie data size exceeds 4K.
Warning! Rack::Session::Cookie failed to save session. Content dropped.
192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /badges/all HTTP/1.1" 200 311
- -> /badges/all
192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /moves/ranking/all HTTP/1.1" 500 166185
- -> /moves/ranking/all
我不知道如何关闭那些 cookie 警告,尽管它们似乎对应用程序没有影响。以下是我如何配置我的应用程序(在我需要的主脚本的配置文件中):
enable :logging
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use Rack::Session::Cookie, :key => 'rack.session',
:path => '/',
:expire_after => 31_536_000, # In seconds
:secret => 'jeowkfj...secret...kjn5'
ActiveRecord::Base.include_root_in_json = false
def establish_connection(url)
db = URI.parse(url)
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
end
configure :development do
establish_connection('postgres://postgres:postgres@localhost:5432/emm')
end
configure :test do
establish_connection('postgres://postgres:postgres@localhost:5432/emm-test')
end
configure :production do
establish_connection(ENV['DATABASE_URL'])
end
我猜我没有正确设置 ActiveRecord,但我认为它就像我看到的教程一样。给了什么?
最佳答案
听起来您正在使用线程,但您的应用程序中有一些非线程安全代码。
您使用的是哪个网络服务器,您使用的是哪个中间件,您使用的是哪个 postgresql gem,您是否检查过所有的 gem 都是线程安全的?
关于ruby - Sinatra/ActiveRecord 无法处理并发请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663079/