springboot2.x 整合mybatis-plus sharding-jdbc实现读写分离

首先,导入依赖,下面只展示核心依赖

     <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.0-betaversion>
        dependency>
        <dependency>
            <groupId>io.shardingjdbcgroupId>
            <artifactId>sharding-jdbc-coreartifactId>
            <version>2.0.3version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.40version>
        dependency>

接下来是我们的配置

首先是MybatisPlusConfig的配置,主要是配置了几个插件,可以按照个人需求配置
@Configuration
public class MybatisPlusConfig {
    /**
     * 分页插件
     *
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 性能分析插件
     *
     * @return
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     * 乐观锁插件
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


}

接下来是sharding-jdbc的配置,需要配置dataSource和主从规则

@Configuration
@EnableConfigurationProperties(ShardingMasterSlaveConfig.class)
@Log4j2
@ConditionalOnProperty({"sharding.jdbc.data-sources.ds_master.jdbc-url", "sharding.jdbc.master-slave-rule.master-data-source-name"})
public class ShardingDataSourceConfig {

    @Autowired
    private ShardingMasterSlaveConfig shardingMasterSlaveConfig;

    @Bean
    public DataSource masterSlaveDataSource() throws SQLException {
        Map dataSourceMap = Maps.newHashMap();
        dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
        DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, shardingMasterSlaveConfig.getMasterSlaveRule(), Maps.newHashMap());
        log.info("masterSlaveDataSource config complete");
        return dataSource;
    }

}
**********************************************************************************************
@Data
@ConfigurationProperties(prefix = "sharding.jdbc")
public class ShardingMasterSlaveConfig {

    private Map dataSources = new HashMap<>();

    private MasterSlaveRuleConfiguration masterSlaveRule;
}

然后是,mapper 和xml,这里就不写了(这里我测试项目中至少需要一个mapper和xml,否则会报空指针异常)。然后controller测试

@RestController
@Log4j2
public class UserController {

    @PostMapping("user")
    public String saveUser(@RequestBody User user) {
        log.info(user);
        user.insert();
        return "插入完毕";
    }
}

下面是测试截图
这里写图片描述

完整项目地址(点我跳转)

你可能感兴趣的:(springboot)