利用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主从切换导致锁失效怎么办? 我说,别着急,这些都是小问题. 那么,关于" ...
随机推荐
- WMS、WFS、WCS、WPS、WMTS、WMSC、TMS等常见地图服务的区别
WebGIS的开发者经常需要面对各种地图服务规范,例如WMS.WFS.WCS.WPS.WMTS.TMS.WMSC等.因此了解这些服务的内容是相当重要的,这里对常见的服务进行了整理. OGC联盟: 开放 ...
- HMS Core Discovery第14期回顾长文|纵享丝滑剪辑,释放视频创作力
HMS Core Discovery第14期直播<纵享丝滑剪辑,释放视频创作力>,已于4月21日圆满结束,本期直播我们同HMS Core视频编辑服务(Video Editor Kit)的产 ...
- Java基础语法Day_06(面相对象和封装)
第1节 描述类介绍与使用 day06_01_面向对象思想的概述 day06_02_面向对象思想的举例 day06_03_类和对象的关系 day06_04_类的定义 day06_05_对象的创建及其使用 ...
- macOS 安装 Nebula Graph 看这篇就够了
本文首发于 Nebula Graph Community 公众号 背景 刚学习图数据的内容,当前网上充斥大量的安装文档,参差不齐,部署起来令人十分头疼. 现整理一份比较完整的安装文档,供大家学习参考, ...
- 让交互更加生动!有意思的鼠标跟随 3D 旋转动效
今天,群友问了这样一个问题,如下所示的鼠标跟随交互效果,如何实现: 简单分析一下,这个交互效果主要有两个核心: 借助了 CSS 3D 的能力 元素的旋转需要和鼠标的移动相结合 本文,就将讲述如何使用纯 ...
- [AcWing 823] 排列
点击查看代码 #include<iostream> using namespace std; const int N = 10; int n; void dfs(int u, int nu ...
- C++进阶-3-5-list容器
C++进阶-3-5-list容器 1 #include<iostream> 2 #include<list> 3 #include<algorithm> 4 usi ...
- unity---射线
射线 Ray ray= Camera.main.ScreenPointToRay(Input.mousePosition);//获得鼠标射向的射线 RaycastHit hit;//射线碰撞物体 if ...
- Python数据分析--Numpy常用函数介绍(2)
摘要:本篇我们将以分析历史股价为例,介绍怎样从文件中载入数据,以及怎样使用NumPy的基本数学和统计分析函数.学习读写文件的方法,并尝试函数式编程和NumPy线性代数运算,来学习NumPy的常用函数. ...
- K8S 使用Minikube搭建Kubernetes(K8S)~单机运行Kubernetes~适用于快速学习
在一台主机上运行起来的Kubernetes,仅适用于学习!~~~ 系统版本:CentOS Linux release 7.6.1810 (Core) 软件版本:Docker-ce-18.06.0.Ku ...