在写入数据库的时候需要有锁,比如同时写入数据库的时候会出现丢数据,那么就需要锁机制。
数据锁分为乐观锁和悲观锁
它们使用的场景如下:
乐观锁适用于写少读多的情景,因为这种乐观锁相当于java的cas,所以多条数据同时过来的时候,不用等待,可以立即进行返回。
悲观锁适用于写多读少的情景,这种情况也相当于java的synchronized,reentrantlock等,大量数据过来的时候,只有一条数据可以被写入,其他的数据需要等待。执行完成后下一条数据可以继续。
他们实现的方式上有所不同。
乐观锁采用版本号的方式,即当前版本号如果对应上了就可以写入数据,如果判断当前版本号不一致,那么就不会更新成功,
比如
update table set column = value
where version=${version} and otherkey = ${otherkey}
悲观锁实现的机制一般是在执行更新语句的时候采用for update方式,
比如
update table set column='value'for update
这种情况where条件呢一定要涉及到数据库对应的索引字段,这样才会是行级锁,否则会是表锁,这样执行速度会变慢。
下面我就弄一个spring boot(springboot 2.1.1 + mysql + lombok + aop + jpa)工程,然后逐渐的实现乐观锁和悲观锁。
假设有一个场景,有一个catalog商品目录表,然后还有一个browse浏览表,假如一个商品被浏览了,那么就需要记录下浏览的user是谁,并且记录访问的总数。
表的结构非常简单:
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 '浏览数',
version int(11) not null default 0 comment '乐观锁,版本号',
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 '创建时间',
primary key(id)
) engine=innodb default charset=utf8;
pom.xml的依赖如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.1.release
com.hqs
dblock
1.0-snapshot
dblock
demo project for spring boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
org.projectlombok
lombok
true
org.aspectj
aspectjweaver
1.8.4
org.springframework.boot
spring-boot-maven-plugin
项目的结构如下:
介绍一下项目的结构的内容:
entity包: 实体类包。
repository包:数据库repository
service包: 提供服务的service
controller包: 控制器写入用于编写requestmapping。相关请求的入口类
annotation包: 自定义注解,用于重试。
aspect包: 用于对自定义注解进行切面。
dblockapplication: springboot的启动类。
dblockapplicationtests: 测试类。
咱们看一下核心代码的实现,参考如下,使用datajpa非常方便,集成了crudrepository就可以实现简单的crud,非常方便,有兴趣的同学可以自行研究。
实现乐观锁的方式有两种:
1、更新的时候将version字段传过来,然后更新的时候就可以进行version判断,如果version可以匹配上,那么就可以更新(方法:updatecatalogwithversion)。
2、在实体类上的version字段上加入version,可以不用自己写sql语句就可以它就可以自行的按照version匹配和更新,是不是很简单。
publicinterfacecatalogrepositoryextendscrudrepository {
@query(value = select * from catalog a where a.id = :id for update, nativequery = true)
optional findcatalogsforupdate(@param(id) long id);
@lock(value = lockmodetype.pessimistic_write) //代表行级锁
@query(select a from catalog a where a.id = :id)
optional findcatalogwithpessimisticlock(@param(id) long id);
@modifying(clearautomatically = true) //修改时需要带上
@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);
}
实现悲观锁的时候也有两种方式:
1、自行写原生sql,然后写上for update语句。(方法:findcatalogsforupdate)
2、使用@lock注解,并且设置值为lockmodetype.pessimistic_write即可代表行级锁。
还有我写的测试类,方便大家进行测试:
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)
publicclassdblockapplicationtests {
@autowired
privatetestresttemplate testresttemplate;
@test
publicvoid browsecatalogtest() {
string url = http://localhost:8888/catalog;
for(int i = 0; i {
multivaluemap params = newlinkedmultivaluemap();
params.add(catalogid, 1);
params.add(user, user + num);
string result = testresttemplate.postforobject(url, params, string.class);
system.out.println(------------- + result);
}
).start();
}
}
@test
publicvoid browsecatalogtestretry() {
string url = http://localhost:8888/catalogretry;
for(int i = 0; i {
multivaluemap params = newlinkedmultivaluemap();
params.add(catalogid, 1);
params.add(user, user + num);
string result = testresttemplate.postforobject(url, params, string.class);
system.out.println(------------- + result);
}
).start();
}
}
}
调用100次,即一个商品可以浏览一百次,采用悲观锁,catalog表的数据都是100,并且browse表也是100条记录。采用乐观锁的时候,因为版本号的匹配关系,那么会有一些记录丢失,但是这两个表的数据是可以对应上的。
乐观锁失败后会抛出objectoptimisticlockingfailureexception,那么我们就针对这块考虑一下重试,下面我就自定义了一个注解,用于做切面。
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@interfaceretryonfailure {
}
针对注解进行切面,见如下代码。我设置了最大重试次数5,然后超过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
@component
publicclassretryaspect {
publicstaticfinalint max_retry_times = 5;//max retry times
@pointcut(@annotation(com.hqs.dblock.annotation.retryonfailure)) //self-defined pointcount for retryonfailure
publicvoid retryonfailure(){}
@around(retryonfailure()) //around can be execute before and after the point
publicobject doconcurrentoperation(proceedingjoinpoint pjp) throwsthrowable {
int attempts = 0;
do {
attempts++;
try {
pjp.proceed();
} catch (exception e) {
if(e instanceofobjectoptimisticlockingfailureexception ||
e instanceofstaleobjectstateexception) {
log.info(retrying....times:{}, attempts);
if(attempts > max_retry_times) {
log.info(retry excceed the max times..);
throw e;
}
}
}
} while (attempts < max_retry_times);
returnnull;
}
}
应急管理部表示 要完善公交车、长途客车驾驶员安全防护设施
旋进旋涡气体流量计应该如何选型
边缘网络将是5G推动确定性网络的切入点
三雄极光用“光”赋能新零售
SiC集成技术在生物电信号采集设计
数据库的乐观锁和悲观锁的使用场景
中央空调出风口尺寸分类及安装方法
离子注入技术的发展趋势及典型应用
泰雷兹身份和生物识别方案应用于法国新出入境系统
海康威视车检线视频监管系统的功能特性及应用优势
ATP生物荧光细菌快速检测仪的应用及特点介绍
透过安森美医疗产品 剖析医疗应用解决方案
为何各大巨头都瞄准了儿童智能音箱?儿童智能音箱发展还存在哪些困境?
深度剖析RFID在猪肉屠宰环节的应用
高性能音频功率放大器的制作
在SOC环境里面C代码是怎么执行的?
报告预计 2020年全球虚拟现实产业规模将超过2000亿元
Diodes推出工业级碳化硅DMWS120H100SM4 N
俄打造城市防无人机雷达网,保证国家重要城镇目标的安全
2020将成为AI+物流元年