Introduction to the

What is optimism lock

  • What is the optimistic lock and what is the pessimistic lock

The sample

  • Create the Version field in the database
  • The POJO writes the fields and uses annotations@Version
  • Write configuration classes and inject plug-ins

Pojo writes the corresponding field

Writing configuration classes

@EnableTransactionManagementTransaction management is turned on by default
@MapperScan("com.mybatis.mapper")
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor optimisticLocker(a){// Optimistic lock plugin
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        returninterceptor; }}Copy the code

test

    @Test
    public void testOptimisticLocker2(a){
       / / thread 1
        User user = userMapper.selectById(1L);
        user.setName("kk111");
        user.setEmail("**[email protected]" );
       // Thread 2 simulates another thread to perform queue jumping
        User user2 = userMapper.selectById(1L);
        user2.setName("kkk222");
        user2.setEmail("[email protected]");
        userMapper.updateById(user2);
        userMapper.updateById(user);
    }
Copy the code

Only one will succeed


Performance analysis

  • The import relies on using the P6Spy data source
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.9.1</version>
        </dependency>
Copy the code
  • 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.DriverCopy the code
  • spy.properties
#3.2.1 Use above
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1 Use or not configure the following
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# Custom log printing
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
Log output to console
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
Use logging system to record SQL
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
P6spy Driver agent
deregisterdrivers=true
# remove the JDBC URL prefix
useprefix=true
# configuration record Log exceptions, can get rid of the result set of the error, the info of batch, debug, statement, commit, rollback, the result, the resultset.
excludecategories=info,debug,result,commit,resultset
# date format
dateformat=yyyy-MM-dd HH:mm:ss
# The actual driver can be multiple
#driverlist=org.h2.Driver
Whether to enable slow SQL recording
outagedetection=true
Slow SQL record standard 2 seconds
outagedetectioninterval=2
Copy the code