用于测试 Rails API 性能的并行帖子

Parallel Posts to test Rails API performance

我需要测试我的 Rails API 的表现。

为此,我创建了一些 Cucumber 功能,这些功能允许我测试对 API 的单数和批量 post 请求,以及插入 [=] 的通用 @child 15=] 次。类似于:

if insertion == 'bulk'
  Parent.all.each do | test_run |
    number_of_times.times { |i| children << parent.child.new(@child) }
  end
  Child.import children
elsif insertion == 'realtime'
  Parent.all.each do | test_run |
    number_of_times.times { |i| parent.child.create!(@child) }
end

现在我需要做的是插入例如 1000,但将其除以 5 个并行请求。类似下面的代码并行发送了 5 次。我的数据库将同时插入 5 children,每个 "thread".

插入 200 次
200.times { |i| parent.child.create!(@child) }

这可以做到吗?最好使用黄瓜(或类似的),这样我就可以 运行 在 Jenkins 中将其作为 CI.

这将满足您的要求:

num_threads = 5
num_times = 200
threadpool = []

num_threads.times do
  # create a thread to do parallel work in, save the thread to the pool
  threadpool << Thread.new do
    # do the actual work
    Parent.find_each do |parent|
      num_times.times { |i| parent.child.create!(@child) }
    end
  end
end

# call join on each thread to wait for them to finish
threadpool.map &:join

这只使用普通的 Ruby 所以它应该在 jenkins 中工作。