如何允许并发访问同一路由?

时间:2013-12-12 12:47:34

标签: ruby concurrency sinatra thin puma

我有一个简单的Sinatra应用程序,有一条长路线:

get '/jobs/new' do
  logger.info "jobs/new start. Thread = #{Thread.current.inspect}"
  sleep 10
  logger.info "end new..."
  erb :'jobs/new'
end

get '/jobs' do
  erb :'jobs/index'
end

我在路由之间同时访问,但不是同一路径。

一个例子是,当客户端调用/jobs/new(访问期间很长)时,另一个客户端可以并行调用jobs。但是同一路线的并行呼叫不起作用。在这种情况下,Web服务器Puma始终使用相同的线程调用路由:

jobs/new started. Thread = #<Thread:0x007f42b128e600 run>
10 seconds later...
jobs/new ended. Thread = #<Thread:0x007f42b128e600 run>
jobs/new started. Thread = #<Thread:0x007f42b128e600 run> <-- new call. Has to wait till first has finished

其他路由由不同的线程调用。当路线1正在运行时:

jobs/new started. Thread = #<Thread:0x007f42b128e600 run>
2 seconds later...
jobs started. Thread = #<Thread:0x007f541f581a40 run> <--other thread
8 seconds later...
jobs/new ended. Thread = #<Thread:0x007f42b128e600 run>
jobs/new started. Thread = #<Thread:0x007f42b128e600 run>

我尝试使用Thin in Thread模式和Puma运行应用程序,具有相同的行为

1 个答案:

答案 0 :(得分:0)

无论你做了什么,我认为这是不对的。

运行此代码:

# config.ru
require 'bundler'
Bundler.require

get '/jobs/new' do
  logger.info "jobs/new start. Thread = #{Thread.current.inspect}"
  sleep 10
  logger.info "end new..."
  "jobs/new"
end

run Sinatra::Application

与美洲狮:

Puma starting in single mode...
* Version 2.7.1, codename: Earl of Sandwich Partition
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://0.0.0.0:9292
Use Ctrl-C to stop
I, [2013-12-12T14:04:48.820907 #9686]  INFO -- : jobs/new start. Thread = #<Thread:0x007fa5667eb7c0 run>
I, [2013-12-12T14:04:50.282718 #9686]  INFO -- : jobs/new start. Thread = #<Thread:0x007fa566731e38 run>
I, [2013-12-12T14:04:58.821509 #9686]  INFO -- : end new...
127.0.0.1 - - [12/Dec/2013 14:04:58] "GET /jobs/new HTTP/1.1" 200 8 10.0132
I, [2013-12-12T14:05:00.283496 #9686]  INFO -- : end new...
127.0.0.1 - - [12/Dec/2013 14:05:00] "GET /jobs/new HTTP/1.1" 200 8 10.0015
^C- Gracefully stopping, waiting for requests to finish
- Goodbye

结果有2个不同的主题!