訪問資料庫 資料庫並行訪問

2021-10-13 20:29:32 字數 2853 閱讀 8185

作者姓名:neo chen (陳景峰)

暱稱:netkiller

呼號:bg7nyt

手機:+86 13113668890

多維度架構 - 知乎​www.zhihu.com

這裡主要講述有關開發中遇到的資料庫並行問題

防止並行顯示背景

我們有乙個order訂單表,工作流如下

建立訂單 -> 訂單分配 -> 訂單審核 -> 批准 -> 發貨 ... 等等
有多個崗位,每個崗位上有多個工作人員。需要實現相同崗位上的工作人員看到的訂單不能重複,防止多人同時操作乙個訂單。

id | user | sn    | status

-----------------------------------

1 | neo | x001 | new

2 | jam | x002 | new

3 | sam | x003 | new

4 | tom | x004 | new

5 | ann | x005 | new

6 | leo | x006 | new

7 | ant | x007 | new

8 | cat | x008 | new

正常情況只要是多人一起開啟訂單頁面就會顯示上面的訂單,並且每個人顯示的內容都相同。

create table `orders` (

`id` int(10) unsigned not null auto_increment,

`name` varchar(50) not null,

`sn` int(10) unsigned zerofill not null,

`status` enum('new','pending','processing','success','failure') not null default 'new',

primary key (`id`),

unique index `sn` (`sn`)

)comment='訂貨單'

collate='utf8_general_ci'

engine=innodb

insert into `orders` (`id`, `name`, `sn`, `status`) values

(1, 'neo', 0000000001, 'new'),

(2, 'jam', 0000000002, 'new'),

(3, 'sam', 0000000003, 'new'),

(4, 'tom', 0000000004, 'new'),

(5, 'ann', 0000000005, 'new'),

(6, 'leo', 0000000006, 'new'),

(7, 'ant', 0000000007, 'new'),

(8, 'cat', 0000000008, 'new');

表 8.1. 工作流模擬

有一種情況,使用者檢視了列表並未及時處理訂單,就會有很多pending狀態的訂單,這是需要有人處理這些訂單,但查詢pending時,可能同一時刻有人在審批訂單,我們通過排他鎖避免重複處理。

上面以mysql為例,每次都需要使用for update 查出要處理的訂單,如果是postgresql 可以使用update + returning 來返回修改的資料,更為方便。

netkiller:資料庫快取​zhuanlan.zhihu.com

netkiller:資料庫結構版本控制​zhuanlan.zhihu.com

netkiller:資料庫記錄安全解決方案​zhuanlan.zhihu.com

netkiller:資料庫程序間通訊解決方案(一)​zhuanlan.zhihu.com

netkiller:資料庫程序間通訊解決方案(二)​zhuanlan.zhihu.com

netkiller:mysql 大資料操作注意事項​zhuanlan.zhihu.com

netkiller:mysql 「鎖」詳解​zhuanlan.zhihu.com

netkiller:mysql 「事務」詳解​zhuanlan.zhihu.com

訪問資料庫 訪問資料庫

程式執行的時候,資料都是在記憶體中的。當程式終止的時候,通常都需要將資料儲存到磁碟上,無論是儲存到本地磁碟,還是通過網路儲存到伺服器上,最終都會將資料寫入磁碟檔案。而如何定義資料的儲存格式就是乙個大問題。如果我們自己來定義儲存格式,比如儲存乙個班級所有學生的成績單 名字成績 michael99 bo...

資料庫訪問

1.sqlcommand 建立sqlconnection的例項 using sqlconnection conn new sqlconnection connectionstring 建立sqlcommand的例項 string sql sql語句 sqlcommand cmd new sqlcom...

訪問資料庫

程式執行的時候,資料都是在記憶體中的。當程式終止的時候,通常都需要將資料儲存到磁碟上,無論是儲存到本地磁碟,還是通過網路儲存到伺服器上,最終都會將資料寫入磁碟檔案。而如何定義資料的儲存格式就是乙個大問題。如果我們自己來定義儲存格式,比如儲存乙個班級所有學生的成績單 名字成績 michael 99bo...