利用MySQL中的乐观锁和悲观锁实现分布式锁
背景
对于一些并发量不是很高的场景,使用MySQL的乐观锁实现会比较精简且巧妙。
下面就一个小例子,针对不加锁、乐观锁以及悲观锁这三种方式来实现。
主要是一个用户表,它有一个年龄的字段,然后并发地对其加一,看看结果是否正确。
一些基础实现类
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer age;
private String name;
private Long id;
private Long version;
}
public interface UserMapper {
@Results(value = {
@Result(property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
@Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
@Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "version", column = "version", javaType = Long.class, jdbcType = JdbcType.BIGINT),
})
@Select("SELECT id, age, name, version FROM user WHERE id = #{id}")
User getUser(Long id);
@Update("UPDATE user SET age = #{age}, version=version+1 WHERE id = #{id} AND version = #{version}")
Boolean compareAndSetAgeById(Long id, Long version, Integer age);
@Update("UPDATE user SET age = #{age} WHERE id = #{id}")
Boolean setAgeById(Long id, Integer age);
@Select("SELECT id, age, name, version FROM user WHERE id = #{id} for update")
User getUserForUpdate(Long id);
}
private static void exe(CountDownLatch countDownLatch, int threads, Runnable runnable) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threads; i++) {
executorService.execute(() -> {
runnable.run();
countDownLatch.countDown();
});
}
executorService.shutdown();
}
private static User getUser(long id) {
try (SqlSession session = openSession(getDataSource1())) {
UserMapper userMapper = session.getMapper(UserMapper.class);
return userMapper.getUser(id);
}
}
public static SqlSession openSession(DataSource dataSource) {
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(UserMapper.class);
configuration.setCacheEnabled(false);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory.openSession();
}
private static DataSource getDataSource1() {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");
return dataSource;
}
不加锁
private static Boolean addAge(long id, int value) {
Boolean result;
try (SqlSession session = openSession(getDataSource1())) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUser(id);
result = userMapper.setAgeById(user.getId(), user.getAge() + value);
session.commit();
}
return result;
}
public static void main(String[] args) throws Exception {
long id = 1L;
int threads = 50;
CountDownLatch countDownLatch = new CountDownLatch(threads);
log.info("user:{}", getUser(id));
long start = System.currentTimeMillis();
exe(countDownLatch, threads, () -> addAge(1, 1));
countDownLatch.await();
long end = System.currentTimeMillis();
log.info("end - start : {}", end - start);
log.info("user:{}", getUser(id));
}
865 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=0, name=3, id=1, version=0)
1033 [main] INFO cn.eagle.li.mybatis.UpdateMain - end - start : 164
1046 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=9, name=3, id=1, version=0)
从输出可以看出,50个并发,但是执行成功的只有9个,这种实现很明显是有问题的。
乐观锁
private static Boolean compareAndAddAge(long id, int value, int times) {
int time = 0;
Boolean result = false;
while (time++ < times && BooleanUtils.isFalse(result)) {
result = compareAndAddAge(id, value);
}
return result;
}
private static Boolean compareAndAddAge(long id, int value) {
try (SqlSession session = openSession(getDataSource1())) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUser(id);
Boolean result = userMapper.compareAndSetAgeById(id, user.getVersion(), user.getAge() + value);
session.commit();
return result;
}
}
public static void main(String[] args) throws Exception {
long id = 1L;
int threads = 50;
CountDownLatch countDownLatch = new CountDownLatch(threads);
log.info("user:{}", getUser(id));
long start = System.currentTimeMillis();
exe(countDownLatch, threads, () -> addAge(1, 1, 20));
countDownLatch.await();
long end = System.currentTimeMillis();
log.info("end - start : {}", end - start);
log.info("user:{}", getUser(id));
}
758 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=0, name=3, id=1, version=0)
1270 [main] INFO cn.eagle.li.mybatis.UpdateMain - end - start : 509
1277 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=50, name=3, id=1, version=50)
从输出可以看出,并发的情况下,结果是没问题的。
悲观锁
private static Boolean addAgeForUpdate(long id, int value) {
Boolean result;
try (SqlSession session = openSession(getDataSource1())) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUserForUpdate(id);
result = userMapper.setAgeById(id, user.getAge() + value);
session.commit();
}
return result;
}
public static void main(String[] args) throws Exception {
long id = 1L;
int threads = 50;
CountDownLatch countDownLatch = new CountDownLatch(threads);
log.info("user:{}", getUser(id));
long start = System.currentTimeMillis();
exe(countDownLatch, threads, () -> addAgeForUpdate(1, 1));
countDownLatch.await();
long end = System.currentTimeMillis();
log.info("end - start : {}", end - start);
log.info("user:{}", getUser(id));
}
631 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=0, name=3, id=1, version=50)
829 [main] INFO cn.eagle.li.mybatis.UpdateMain - end - start : 196
837 [main] INFO cn.eagle.li.mybatis.UpdateMain - user:User(age=50, name=3, id=1, version=50)
从输出可以看出,并发的情况下,结果是没问题的。
总结
从以上来看,乐观锁和悲观锁实现都是没有问题的,至于选哪一种,还是要看业务的场景,比如说并发量的多少,加锁时长等等。
利用MySQL中的乐观锁和悲观锁实现分布式锁的更多相关文章
- mysql中的乐观锁和悲观锁
mysql中的乐观锁和悲观锁的简介以及如何简单运用. 关于mysql中的乐观锁和悲观锁面试的时候被问到的概率还是比较大的. mysql的悲观锁: 其实理解起来非常简单,当数据被外界修改持保守态度,包括 ...
- 图解Janusgraph系列-并发安全:锁机制(本地锁+分布式锁)分析
图解Janusgraph系列-并发安全:锁机制(本地锁+分布式锁)分析 大家好,我是洋仔,JanusGraph图解系列文章,实时更新~ 图数据库文章总目录: 整理所有图相关文章,请移步(超链):图数据 ...
- SpringBoot--防止重复提交(锁机制---本地锁、分布式锁)
防止重复提交,主要是使用锁的形式来处理,如果是单机部署,可以使用本地缓存锁(Guava)即可,如果是分布式部署,则需要使用分布式锁(可以使用zk分布式锁或者redis分布式锁),本文的分布式锁以red ...
- Spring Boot 2实现分布式锁——这才是实现分布式锁的正确姿势!
参考资料 网址 Spring Boot 2实现分布式锁--这才是实现分布式锁的正确姿势! http://www.spring4all.com/article/6892
- 老司机带大家领略MySQL中的乐观锁和悲观锁
原文地址:https://cloud.tencent.com/developer/news/227982 为什么需要锁 在并发环境下,如果多个客户端访问同一条数据,此时就会产生数据不一致的问题,如何解 ...
- MYSQL中的乐观锁实现(MVCC)简析
https://segmentfault.com/a/1190000009374567#articleHeader2 什么是MVCC MVCC即Multi-Version Concurrency Co ...
- 分布式锁(一) Zookeeper分布式锁
什么是Zookeeper? Zookeeper(业界简称zk)是一种提供配置管理.分布式协同以及命名的中心化服务,这些提供的功能都是分布式系统中非常底层且必不可少的基本功能,但是如果自己实现这些功能而 ...
- 分布式锁之三:Redlock实现分布式锁
之前写过一篇文章<如何在springcloud分布式系统中实现分布式锁?>,由于自己仅仅是阅读了相关的书籍,和查阅了相关的资料,就认为那样的是可行的.那篇文章实现的大概思路是用setNx命 ...
- 【面试普通人VS高手系列】请说一下你对分布式锁的理解,以及分布式锁的实现
一个工作了7年的Java程序员,私信我关于分布式锁的问题. 一上来就两个灵魂拷问: Redis锁超时怎么办? Redis主从切换导致锁失效怎么办? 我说,别着急,这些都是小问题. 那么,关于" ...
随机推荐
- DOS攻击(一)
DOS攻击(一) 介绍 DoS是Denial of Service的简称,即拒绝服务,造成DoS的攻击行为被称为DoS攻击,其目的是使计算机或网络无法提供正常的服务.最常见的DoS攻击有计算机网络带宽 ...
- python基础练习题(题目 求输入数字的平方,如果平方运算后小于 50 则退出)
day32 --------------------------------------------------------------- 实例046:打破循环 题目 求输入数字的平方,如果平方运算后 ...
- 【GPLT】 紧急救援(c++)
题目: 本题使用Dijkstra算法,但在模板上进行了一定的扩展,是一道不错的最短路题目. AC代码: 1 #include<iostream> 2 #include<cmath&g ...
- Python实现双X轴双Y轴绘图
诈尸人口回归.这一年忙着灌水忙到头都掉了,最近在女朋友的提醒下终于想起来博客的账号密码,正好今天灌水的时候需要画一个双X轴双Y轴的图,研究了两小时终于用Py实现了.找资料的过程中没有发现有系统的文章, ...
- Go通过cobra快速构建命令行应用
来自jetbrains Go 语言现状调查报告 显示:在go开发者中使用go开发实用小程序的比例为31%仅次于web,go得益于跨平台.无依赖的特性,用来编写命令行或系统管理这类小程序非常不错. 本文 ...
- PicLite 开发日志 (v0.0.3)
PicLite 开发日志 (v0.0.3) 感谢您阅读本片文章! Gitee 地址:https://gitee.com/XiaoQuQuSD/pic-lite. 新增功能 当错误出现时不再强制 rai ...
- python学习-Day9
目录 记忆不清点回顾 今日概要 今日内容 大作业讲解 字符编码实际应用 编码与解码 如何解决乱码的问题 文件操作简介 什么是文件 代码操作文件 代码操作文件的流程 基本语法结构 使用关键字打开文件 w ...
- 看完复旦博士用Python统计核酸结果后,我照着也写了一个
前几天,人民日报公众号报道了复旦博士生自己写代码,通过OCR和正则表达式统计核酸截图结果.具体文章见:https://mp.weixin.qq.com/s/l8u9JifKDlRDoz32-jZWQg ...
- 2020年DevOps工程师入门指南
DevOps兴起于2010年代,到现在DevOps已经在行业中拥有了一席之地,并在继续发展壮大. 有兴趣成为一名DevOps工程师吗?如果想要成为一名DevOps工程师,需要做到以下五点: 要有开发者 ...
- python入门基础知识三(列表和元组)
列表(list)的操作 1. 形式 var = ['char1','char2','char3',...] var = [value1,value2,value3,...] 2. 列表的增删改查 查: ...