在高并发场景下,用户请求几乎同时到达服务器时,count()方法和实际插入数据的操作之间存在时间窗口,可能导致多个请求都通过了“已选择”检查,从而插入了多条记录。
我的解决方案
前端增加随机时间
每个用户点击提交按钮后按照随机时间倒计时完成后自动提交
示例代码:
layer.alert('数据提交中,请勿关闭页面...', {
time: parseInt(Math.random() * 25 + 1) * 1000,
// time: parseInt(Math.random() * (25 - 1 + 1) + 1)*1000,//用于生成1到25之间的随机整数并将其乘以1000:
closeBtn: 0
,skin: 'yanshi' //样式类名
,success: function(layero, index){
var timeNum = this.time/1000, setText = function(start){
layer.title((start ? timeNum : --timeNum) + ' 秒后自动关闭', index);
};
setText(!0);
this.timer = setInterval(setText, 1000);
if(timeNum <= 0) clearInterval(this.timer);
}
,end: function(){
disableButton(submitBtn, false);
clearInterval(this.timer);
$.post("{:url('course/index/index',['classid'=>$Think.config.app.sys.id,'action'=>'subsave','id'=>111])}", data.field, function(res) {
if (res.code === 200) {
layer.confirm(res.msg, {
closeBtn: 0,
btn: ['确定']
}, function(index, layero){
window.location.replace("{:url('course/index/index',['classid'=>$Think.config.app.sys.id,'action'=>'info'])}");
});
} else {
layer.confirm(res.msg, {
closeBtn: 0,
btn: ['返回修改']
}, function(index, layero){
window.location.replace("{:url('course/index/index',['classid'=>$Think.config.app.sys.id,'action'=>'info'])}");
});
// layer.msg(res.msg, { icon: 2 });
}
}, 'json');
}
});
return false;
后端为user_id添加唯一约束
补充:Navicat 如何添加唯一约束(转自百度经验)
打开 Navicat,在左侧导航栏上找到相应的表格,右键菜单选择”设计表
在设计表编辑区,点击”索引“面板,勾选需要添加唯一值约束的字段,在索引类型栏选择”UNIQUE“。
切换至”SQL预览“面板,我们可以查看相应的 SQL 语句,快捷键”CTRL + S“可以保存设置。