Mybatis-Plus 乐观锁插件和性能分析

简介

何谓乐观锁

样例

  • 在数据库创建version字段
  • pojo写入相应字段,并使用注解@Version
  • 编写配置类,注入插件

pojo写入相应字段

image.png
编写配置类

@EnableTransactionManagement//事务管理默认是打开的
@MapperScan("com.mybatis.mapper")
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor optimisticLocker(){//乐观锁插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

复制代码

test

    @Test
    public void testOptimisticLocker2(){
       //线程1
        User user = userMapper.selectById(1L);
        user.setName("kk111");
        user.setEmail("**24736743@qq.com" );
       //线程二 模拟另外一个线程执行了插队操作
        User user2 = userMapper.selectById(1L);
        user2.setName("kkk222");
        user2.setEmail("24736743@qq.com");
        userMapper.updateById(user2);
        userMapper.updateById(user);
    }
复制代码

只有一个会成功

image.png


image.png

性能分析

  • 导入依赖使用p6spy数据源
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.9.1</version>
        </dependency>
复制代码
  • application.yaml
spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    username: root
    password: 123456
    url: jdbc:p6spy:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
    # driver-class-name: com.mysql.cj.jdbc.Driver
复制代码
  • spy.properties

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享