Mysql解決死鎖問題
死鎖(英語:Deadlock)哎甲,又譯為死結(jié)著榴,計算機(jī)科學(xué)名詞博脑。當(dāng)兩個以上的運算單元憎乙,雙方都在等待對方停止運行,以獲取系統(tǒng)資源叉趣,但是沒有一方提前退出時泞边,就稱為死鎖。 -- 引用自維基百科疗杉。
mysql> select * from user;
+----+------+------+---------+
| id | name | age | address |
+----+------+------+---------+
| 3 | 1 | 26 | 1 |
| 4 | 1 | 1 | 1 |
+----+------+------+---------+
有一張user表阵谚,id是主鍵,那么執(zhí)行如下操作會造成死鎖:
A:
start transaction;
select * from user where id=3 for update;
B:
start transaction;
select * from user where id=4 for update;
A:
select * from user where id=4 for update;
B:
select * from user where id=3 for update;
執(zhí)行到這里烟具,A梢什、B兩個數(shù)據(jù)庫連接都會阻塞。
處理死鎖問題:
show processlist # 顯示當(dāng)前DB所有連接信息朝聋,如果有連接處于阻塞狀態(tài)嗡午,則會有如下顯示
阻塞圖例
kill id # 殺死對應(yīng)連接,這樣就會釋放掉占用的鎖
show engine innodb status # 顯示索引狀態(tài)冀痕,因為innodb引擎會在索引上進(jìn)行加鎖,執(zhí)行這條語句會返回引擎的各種信息(比如):
TRANSACTIONS
------------
Trx id counter 69598
Purge done for trx's n:o < 69594 undo n:o < 0 state: running but idle
History list length 1036
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 281479623174360, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 281479623173456, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 281479623170744, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 281479623169840, not started
0 lock struct(s), heap size 1136, 0 row lock(s)
---TRANSACTION 69597, ACTIVE 89 sec
2 lock struct(s), heap size 1136, 1 row lock(s) # 顯示該事務(wù)鎖住一行數(shù)據(jù)
MySQL thread id 1124, OS thread handle 123145506287616, query id 130081 localhost root cleaning up
--------
Maven 引入本地jar包
<dependency>
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>/.../xxx.jar</systemPath>
</dependency>
這種方法是有缺陷的荔睹,僅僅適用于開發(fā)階段,如果使用 maven package 命令不會把該包打入jar中言蛇。
這個缺陷有一種比較好的解決方案是參考鏈接中 Nikita Volkov 回答的方法僻他。
MySql連接問題
給朋友寫的腳本要把數(shù)據(jù)插入MySql數(shù)據(jù)庫,在本地測試插入沒有問題腊尚;但是在朋友機(jī)器上插入之后出現(xiàn)亂碼吨拗。
配置如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
出現(xiàn)的亂碼都是??,所以估計是把UTF-8編碼格式當(dāng)做ISO-8859-1進(jìn)行編碼。
把上述配置修改后插入正常婿斥。
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
useUnicode=true&characterEncoding=UTF-8代表使用指定的編碼集UTF-8來進(jìn)行編碼劝篷。
那么為什么本地沒有問題而朋友機(jī)器上有問題呢,原因是本地MySql服務(wù)器和數(shù)據(jù)庫都是以UTF-8編碼的受扳;而朋友機(jī)器上僅僅數(shù)據(jù)庫是UTF-8編碼的携龟,如果沒有指定編碼格式數(shù)據(jù)庫會按照默認(rèn)ISO-8859-1進(jìn)行編碼從而導(dǎo)致亂碼。