您好,登錄后才能下訂單哦!
工作中經(jīng)常會(huì)對(duì)一列數(shù)據(jù)進(jìn)行自增操作,設(shè)想一個(gè)場景。
總共發(fā)放10張優(yōu)惠券(以下的操作以時(shí)間為序列)
1)用戶1請(qǐng)求領(lǐng)取1張優(yōu)惠券;
2)進(jìn)程1查詢到數(shù)據(jù)庫中剩余10張,代碼更新優(yōu)惠券數(shù)量,此時(shí)為內(nèi)存中優(yōu)惠券數(shù)量為9;
3)此時(shí),用戶2請(qǐng)求領(lǐng)取1張優(yōu)惠券。進(jìn)程1并未將9寫入到數(shù)據(jù)庫中,所以此時(shí)進(jìn)程2取到的優(yōu)惠券的數(shù)量還是10。進(jìn)程2計(jì)算數(shù)量,內(nèi)存中的優(yōu)惠券數(shù)量為9;
4)進(jìn)程1更新數(shù)據(jù)庫優(yōu)惠券的數(shù)量,number = 9;
5)進(jìn)程2更新數(shù)據(jù)庫優(yōu)惠券的數(shù)量,number = 9;
實(shí)際上已經(jīng)發(fā)出去了兩張優(yōu)惠券,但是數(shù)據(jù)庫中還剩9張優(yōu)惠券。
所以呢,將數(shù)據(jù)load到內(nèi)存中加減完成再入庫是有點(diǎn)風(fēng)險(xiǎn)的。
兩種解決方案:
1)加鎖,別管是加個(gè)樂觀鎖還是悲觀鎖,這個(gè)不細(xì)聊了;
2)不在內(nèi)存中加,直接在數(shù)據(jù)庫層面進(jìn)行set number = number - 1;在Laravel中,有increment和decrement封裝來實(shí)現(xiàn)操作。
increment:
public function increment($column, $amount = 1, array $extra = [])
{
if (! is_numeric($amount)) {
throw new InvalidArgumentException('Non-numeric value passed to increment method.');
}
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
return $this->update($columns);
}
decrement:
public function decrement($column, $amount = 1, array $extra = [])
{
if (! is_numeric($amount)) {
throw new InvalidArgumentException('Non-numeric value passed to decrement method.');
}
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);
return $this->update($columns);
}
都調(diào)用了update方法,看一下update:
public function update(array $values)
{
$sql = $this->grammar->compileUpdate($this, $values);
var_dump($sql); // 打印一下sql語句
return $this->connection->update($sql, $this->cleanBindings(
$this->grammar->prepareBindingsForUpdate($this->bindings, $values)
));
}
用兩種方式進(jìn)行數(shù)據(jù)庫修改:
1)直接修改數(shù)量
$res = self::where('id', $data['id'])->update(['number' => self::raw('number + 1')] );
查看輸出的sql語句:
update coupon set number = ? where id = ?
2)用decrement
$res = self::where('id', $data['id'])->decrement('number', 2);
查看sql輸出結(jié)果:
update coupon set number = number - 2 where id = ?;
所以并發(fā)較多的情況下建議使用increment和decrement。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。