久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java中數(shù)據(jù)庫(kù)常用的兩把鎖之樂(lè)觀鎖和悲觀鎖

瀏覽:4日期:2022-08-28 11:53:46

在寫(xiě)入數(shù)據(jù)庫(kù)的時(shí)候需要有鎖,比如同時(shí)寫(xiě)入數(shù)據(jù)庫(kù)的時(shí)候會(huì)出現(xiàn)丟數(shù)據(jù),那么就需要鎖機(jī)制。

數(shù)據(jù)鎖分為樂(lè)觀鎖和悲觀鎖,那么它們使用的場(chǎng)景如下:

1. 樂(lè)觀鎖適用于寫(xiě)少讀多的情景,因?yàn)檫@種樂(lè)觀鎖相當(dāng)于JAVA的CAS,所以多條數(shù)據(jù)同時(shí)過(guò)來(lái)的時(shí)候,不用等待,可以立即進(jìn)行返回。

2. 悲觀鎖適用于寫(xiě)多讀少的情景,這種情況也相當(dāng)于JAVA的synchronized,reentrantLock等,大量數(shù)據(jù)過(guò)來(lái)的時(shí)候,只有一條數(shù)據(jù)可以被寫(xiě)入,其他的數(shù)據(jù)需要等待。執(zhí)行完成后下一條數(shù)據(jù)可以繼續(xù)。

他們實(shí)現(xiàn)的方式上有所不同,樂(lè)觀鎖采用版本號(hào)的方式,即當(dāng)前版本號(hào)如果對(duì)應(yīng)上了就可以寫(xiě)入數(shù)據(jù),如果判斷當(dāng)前版本號(hào)不一致,那么就不會(huì)更新成功,比如 update table set column = value where version=${version} and otherKey = ${otherKey}。悲觀鎖實(shí)現(xiàn)的機(jī)制一般是在執(zhí)行更新語(yǔ)句的時(shí)候采用for update方式,比如 update table set column=’value’ for update。這種情況where條件呢一定要涉及到數(shù)據(jù)庫(kù)對(duì)應(yīng)的索引字段,這樣才會(huì)是行級(jí)鎖,否則會(huì)是表鎖,這樣執(zhí)行速度會(huì)變慢。

下面我就弄一個(gè)spring boot(springboot 2.1.1 + mysql + lombok + aop + jpa)工程,然后逐漸的實(shí)現(xiàn)樂(lè)觀鎖和悲觀鎖。假設(shè)有一個(gè)場(chǎng)景,有一個(gè)catalog商品目錄表,然后還有一個(gè)browse瀏覽表,假如一個(gè)商品被瀏覽了,那么就需要記錄下瀏覽的user是誰(shuí),并且記錄訪問(wèn)的總數(shù)。

表的結(jié)構(gòu)非常簡(jiǎn)單:

create table catalog (id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ’主鍵’,name varchar(50) NOT NULL DEFAULT ’’ COMMENT ’商品名稱’,browse_count int(11) NOT NULL DEFAULT 0 COMMENT ’瀏覽數(shù)’,version int(11) NOT NULL DEFAULT 0 COMMENT ’樂(lè)觀鎖,版本號(hào)’,PRIMARY KEY(id)) ENGINE=INNODB DEFAULT CHARSET=utf8;CREATE table browse (id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ’主鍵’,cata_id int(11) NOT NULL COMMENT ’商品ID’,user varchar(50) NOT NULL DEFAULT ’’ COMMENT ’’,create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ’創(chuàng)建時(shí)間’,PRIMARY KEY(id)) ENGINE=INNODB DEFAULT CHARSET=utf8;

 POM.XML的依賴如下:

<?xml version='1.0' encoding='UTF-8'?><project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.hqs</groupId> <artifactId>dblock</artifactId> <version>1.0-SNAPSHOT</version> <name>dblock</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- aop --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>

項(xiàng)目的結(jié)構(gòu)如下:

Java中數(shù)據(jù)庫(kù)常用的兩把鎖之樂(lè)觀鎖和悲觀鎖

介紹一下項(xiàng)目的結(jié)構(gòu)的內(nèi)容:

entity包: 實(shí)體類包。

repository包:數(shù)據(jù)庫(kù)repository

service包: 提供服務(wù)的service

controller包: 控制器寫(xiě)入用于編寫(xiě)requestMapping。相關(guān)請(qǐng)求的入口類

annotation包: 自定義注解,用于重試。

aspect包: 用于對(duì)自定義注解進(jìn)行切面。

DblockApplication: springboot的啟動(dòng)類。

DblockApplicationTests: 測(cè)試類。

咱們看一下核心代碼的實(shí)現(xiàn),參考如下,使用dataJpa非常方便,集成了CrudRepository就可以實(shí)現(xiàn)簡(jiǎn)單的CRUD,非常方便,有興趣的同學(xué)可以自行研究。

實(shí)現(xiàn)樂(lè)觀鎖的方式有兩種:

1. 更新的時(shí)候?qū)ersion字段傳過(guò)來(lái),然后更新的時(shí)候就可以進(jìn)行version判斷,如果version可以匹配上,那么就可以更新(方法:updateCatalogWithVersion)。

2. 在實(shí)體類上的version字段上加入version,可以不用自己寫(xiě)SQL語(yǔ)句就可以它就可以自行的按照version匹配和更新,是不是很簡(jiǎn)單。 

public interface CatalogRepository extends CrudRepository<Catalog, Long> { @Query(value = 'select * from Catalog a where a.id = :id for update', nativeQuery = true) Optional<Catalog> findCatalogsForUpdate(@Param('id') Long id); @Lock(value = LockModeType.PESSIMISTIC_WRITE) //代表行級(jí)鎖 @Query('select a from Catalog a where a.id = :id') Optional<Catalog> findCatalogWithPessimisticLock(@Param('id') Long id); @Modifying(clearAutomatically = true) //修改時(shí)需要帶上 @Query(value = 'update Catalog set browse_count = :browseCount, version = version + 1 where id = :id ' + 'and version = :version', nativeQuery = true) int updateCatalogWithVersion(@Param('id') Long id, @Param('browseCount') Long browseCount, @Param('version') Long version);}

實(shí)現(xiàn)悲觀鎖的時(shí)候也有兩種方式:

1. 自行寫(xiě)原生SQL,然后寫(xiě)上for update語(yǔ)句。(方法:findCatalogsForUpdate)

2. 使用@Lock注解,并且設(shè)置值為L(zhǎng)ockModeType.PESSIMISTIC_WRITE即可代表行級(jí)鎖。

還有我寫(xiě)的測(cè)試類,方便大家進(jìn)行測(cè)試:

package com.hqs.dblock;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.test.web.client.TestRestTemplate;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.util.LinkedMultiValueMap;import org.springframework.util.MultiValueMap;@RunWith(SpringRunner.class)@SpringBootTest(classes = DblockApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public class DblockApplicationTests { @Autowired private TestRestTemplate testRestTemplate; @Test public void browseCatalogTest() { String url = 'http://localhost:8888/catalog'; for(int i = 0; i < 100; i++) { final int num = i; new Thread(() -> { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add('catalogId', '1'); params.add('user', 'user' + num); String result = testRestTemplate.postForObject(url, params, String.class); System.out.println('-------------' + result); } ).start(); } } @Test public void browseCatalogTestRetry() { String url = 'http://localhost:8888/catalogRetry'; for(int i = 0; i < 100; i++) { final int num = i; new Thread(() -> { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add('catalogId', '1'); params.add('user', 'user' + num); String result = testRestTemplate.postForObject(url, params, String.class); System.out.println('-------------' + result); } ).start(); } }}

調(diào)用100次,即一個(gè)商品可以瀏覽一百次,采用悲觀鎖,catalog表的數(shù)據(jù)都是100,并且browse表也是100條記錄。采用樂(lè)觀鎖的時(shí)候,因?yàn)榘姹咎?hào)的匹配關(guān)系,那么會(huì)有一些記錄丟失,但是這兩個(gè)表的數(shù)據(jù)是可以對(duì)應(yīng)上的。

樂(lè)觀鎖失敗后會(huì)拋出ObjectOptimisticLockingFailureException,那么我們就針對(duì)這塊考慮一下重試,下面我就自定義了一個(gè)注解,用于做切面。

package com.hqs.dblock.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface RetryOnFailure {}

針對(duì)注解進(jìn)行切面,見(jiàn)如下代碼。我設(shè)置了最大重試次數(shù)5,然后超過(guò)5次后就不再重試。

package com.hqs.dblock.aspect;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.hibernate.StaleObjectStateException;import org.springframework.orm.ObjectOptimisticLockingFailureException;import org.springframework.stereotype.Component;@Slf4j@Aspect@Componentpublic class RetryAspect { public static final int MAX_RETRY_TIMES = 5;//max retry times @Pointcut('@annotation(com.hqs.dblock.annotation.RetryOnFailure)') //self-defined pointcount for RetryOnFailure public void retryOnFailure(){} @Around('retryOnFailure()') //around can be execute before and after the point public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int attempts = 0; do { attempts++; try { pjp.proceed(); } catch (Exception e) { if(e instanceof ObjectOptimisticLockingFailureException || e instanceof StaleObjectStateException) { log.info('retrying....times:{}', attempts); if(attempts > MAX_RETRY_TIMES) { log.info('retry excceed the max times..'); throw e; } } } } while (attempts < MAX_RETRY_TIMES); return null; }}

大致思路是這樣了,歡迎拍磚。

GIT代碼:https://github.com/stonehqs/dblock

到此這篇關(guān)于數(shù)據(jù)庫(kù)常用的兩把鎖之樂(lè)觀鎖和悲觀鎖的文章就介紹到這了,更多相關(guān)數(shù)據(jù)庫(kù)鎖 樂(lè)觀鎖 悲觀鎖內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 梧州市| 尉犁县| 田东县| 乐至县| 芦山县| 新密市| 宁都县| 大余县| 宝应县| 调兵山市| 巴林右旗| 开原市| 景谷| 汶川县| 海兴县| 定结县| 光泽县| 时尚| 上栗县| 朝阳县| 景洪市| 通道| 鹰潭市| 佛冈县| 保定市| 成武县| 承德市| 新源县| 巴林右旗| 炎陵县| 漳州市| 曲水县| 阿拉尔市| 泰和县| 巴林右旗| 习水县| 灌阳县| 凤城市| 彰化县| 澄迈县| 珲春市|