我在我的网络应用程序中使用 Tornado 。 mysqldb用于向mysql5.1插入数据。 在生产环境中,有一个nginx+上游,有10个tornado进程。 当网络速度较慢时,用户双击按钮并将相同的json数据发送到tornado handler,有时会在mysql中生成两行相同的数据。实际上,我使用了mysqldb事务并测试了逻辑。开发环境下没问题(一个tornado进程)。
我的代码:
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 吗?
最佳答案
你有竞争条件。在生产中更容易看到,因为您是通过延迟较高的网络进行发布,因此您有更多时间在第一次 INSERT 完成之前单击按钮两次。典型的解决方案是在按钮发布到服务器之前使用 JavaScript 使其自身禁用,以防止双击。请参阅this answer有关等待 AJAX 请求完成时禁用按钮的示例。
关于python - mysql 中的同一行(nginx+tornado+mysqldb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27313413/