2014-12-05 13 views
0

我爲我的web應用程序使用龍捲風。 mysqldb用於將數據插入到mysql5.1中。 在生產環境中,nginx +上游有10個龍捲風過程。 當網絡速度較慢時,用戶將雙擊該按鈕並將相同的json數據發佈爲龍捲風處理程序,有時會在mysql中生成兩行具有相同數據的行。實際上,我使用mysqldb transcation來測試邏輯。在開發環境中是可以的(一個龍捲風過程)。mysql中的同一行(nginx + tornado + mysqldb)

我的代碼:

import MySQLdb 
    hostname = options.mysql_host 
    uid = options.mysql_user 
    database = options.mysql_database 
    pwd = options.mysql_password 
    port = 3306 
    newid=-1 
    conn = MySQLdb.connect(host=hostname, user=uid,db=database,passwd=pwd,port=int(port),use_unicode=True,charset="utf8") 
    cursor = conn.cursor() 

    try: 

     sql_query = "select ID from ATable where USER_ID = "+str(_user_id)+" and START_DATE_LOCAL = '"+str(_start_date_local)+"' and FLAG = 1" 
     cursor.execute(sql_query) 
     results_query = cursor.fetchone() 

     if results_query is not None: 
      newid =int(results_query[0]) 
     else: 
      #do insert 
      sql="insert into ATable..." 
      print sql 

      cursor.execute(sql) 
      newid = int(conn.insert_id()) 

     conn.commit() 

    except Exception,e: 
     print 'ERROR:',e 
     conn.rollback() 

    conn.close() 
    return newid 

我覺得我的代碼是正確的。 nginx或mysql5.1可能有問題嗎?

我應該在這個處理程序的nginx upstrem中配置ip_hash嗎?

回答

0

您有一個競賽條件。在生產環境中看起來更容易,因爲您發佈的是更高延遲的網絡,所以在第一次INSERT完成之前,您有更多時間點擊該按鈕兩次。典型的解決方案是使用Javascript 將該按鈕禁用,然後將其發佈到服務器,以防止雙擊。有關在等待AJAX​​請求完成時禁用按鈕的示例,請參閱this answer