2011-12-12 20 views
3

this question with the same title如何解決「Mysql2 ::錯誤:此連接還在等待結果」與mysql2和ActiveRecord的錯誤

不重複我使用ActiveRecord與mysql2和我設計處理10個查詢到相同的主動記錄模型/類一次。 請注意我正在使用嚴格的activerecord,而不是直接使用mysql查詢。

我在Sinatra中獲得調用,然後使用activerecord從數據庫中獲取數據。

我不希望被阻塞,所以我用mysql2,我做不是想要使用em-synchrony。

但是現在,在後續的同時調用中,我得到以下「Mysql2 ::錯誤:此連接仍在等待結果,請在結果後再試一次:」。

我不建立與池連接= 10

我的課

class User < ActiveRecord::Base 

和我的代碼來調用 user.find(:全部:條件=> [ 「ID =?」,用戶ID]

mysql2文件說:「要使用ActiveRecord驅動程序(帶或不帶導軌),所有你需要做的就是安裝這個gem並將你的database.yml中的適配器設置爲」mysql2「。很容易吧?:)「

而這正是我從mysql移動到mysql2時所做的。

爲什麼我得到這個錯誤。

+0

如果你能告訴我們你的應用程序代碼,這將有助於(做一個小例子,放入在github上,如果你不能或不想展示真正的應用程序)。這也取決於你使用什麼http服務器來提供服務。 – Schmurfy

+0

我正在使用Thin支持的Sinatra。我會盡力發揮主要作用。 – Anand

回答

0

您必須使用連接池。 mysql2允許查詢是異步的,但您仍然只能通過一個連接一次向MySQL發送一個查詢。如果您通過一個連接發送多個查詢,則可以等待結果消息。

使用連接池,你應該沒問題。

3

這裏是一個完全工作的例子:

require 'rubygems' 
gem 'activerecord', '~> 3.1.0' 
gem 'sinatra',  '~> 1.3.1' 
gem 'mysql2',  '~> 0.3.11' 

require 'active_record' 
require 'sinatra/base' 
require 'mysql2' 

# thin use the eventmachine thread pool 
# you should have at least one connection per thread 
# or you can expect errors 
EM::threadpool_size = 10 

# connect to the database 
ActiveRecord::Base.establish_connection(
    :adapter => "mysql2", 
    :database => "test", 
    :username => "root", 
    :encoding => 'utf8', 
    # number of connections openened to the database 
    :pool => 10 
) 

class App < Sinatra::Base 
    get '/db' do 
    ActiveRecord::Base.connection.execute("SELECT SLEEP(1)") 
    end 
end 

run App 

運行它將該文件保存爲「config.ru」,並與薄線程模式下運行:

thin start -e production --threaded 

您可以使用AB檢查一切正常,我用了一個工具,稱爲圍攻:

siege -c 10 -r 1 http://localhost:3000/db 
2

您應該使用連接池...不知怎的喲在比賽中你有2個連接。

我不使用西納特拉,我使用Rails的,但我有同樣的問題,並解決了它這樣的:

# class ActiveRecord::Base 
# mattr_accessor :shared_connection 
# @@shared_connection = nil 
# 
# def self.connection 
#  @@shared_connection || retrieve_connection 
# end 
# end 
# 
# ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection 

class ActiveRecord::Base 
    mattr_accessor :shared_connection 
    @@shared_connection = nil 

    def self.connection 
    @@shared_connection || ConnectionPool::Wrapper.new(:size => 1) { retrieve_connection } 
    end 
end 

ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection 
+0

Ps:由於應用程序和集成測試中使用的webdriver之間的共享連接,我僅在測試環境中出現此問題。 – hsgubert

相關問題