Spring boot+MyBatis+Sharding jdbc配置

为便于在工作中进行单机多服务部署及简化开发配置,将现有系统迁移至Spring boot。

Maven配置

       Spring boot相关依赖:web、jdbc、aop相关依赖包(由于项目中应用了redis,所以一并移植了)

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>1.4.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
 </dependencyManagement>

 <!-- spring boot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
          <!--sharding-jdbc -->
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>sharding-jdbc-core</artifactId>
            <version>${sharding-jdbc.version}</version>
        </dependency>
         <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>

MyBatis配置相关

       mapper配置文件存放于resources目录:

resources/
     mapper/
         xxx.xml
         xxx.xml
         ...

集成Spring boot 配置文件:MyBatisConfig,MyBatisMapperScannerConfig。
参考:abel MyBatis集成

@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {


    @Autowired
    XbDataSource xbDataSource;//集成sharding-jdbc分表数据源

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(xbDataSource.getDataSource());
        bean.setTypeAliasesPackage("com.xiaobai.crawler.model");//实体对应包路径


        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {

        return new DataSourceTransactionManager(xbDataSource.getDataSource());
    }
}
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.xiaobai.crawler.mapper");//mapper类路径
        return mapperScannerConfigurer;
    }

}

sharding-jdbc分表配置

数据源配置及分表规则定义(只对tb_p表按照item_id进行分表13张,tb_item不分表)

@Component
public class XbDataSource {

    @Autowired
    DataSource dataSource;

    DataSource shardingDataSource;

    @PostConstruct
    public void init() {
        HashMap<String, DataSource> map = new HashMap<>();
        map.put("dataSource", dataSource);
        DataSourceRule dataSourceRule = new DataSourceRule(map);

        List<TableRule> tableRuleList = new ArrayList<>();
        List<String> pList = new ArrayList<>();
        for (int i = 1; i < 14; i++) {
            pList.add("tb_p_" + i);
        }
        //tb_p逻辑表名,pList实际所有的分表
        tableRuleList.add(new TableRule.TableRuleBuilder("tb_p")
                .actualTables(pList)
                .dataSourceRule(dataSourceRule)
                .tableShardingStrategy(new TableShardingStrategy("item_id", new ProgramShardingAlgorithm())).build());
        tableRuleList.add(new TableRule.TableRuleBuilder("tb_item")
                .actualTables(Lists.newArrayList("tb_item"))
                .dataSourceRule(dataSourceRule).build());
        ShardingRule shardingRule = ShardingRule.builder()
                .dataSourceRule(dataSourceRule)
                .tableRules(tableRuleList)
                .build();
        shardingDataSource = ShardingDataSourceFactory.createDataSource(shardingRule);
    }

    public DataSource getDataSource() {
        return shardingDataSource;
    }
@Component
public final class ProgramShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> {

    /**
     * equals比较条件
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doEqualSharding(final Collection<String> availableTargetNames, final ShardingValue<Integer> shardingValue) {
        for (String each : availableTargetNames) {
            if (each.endsWith(shardingValue.getValue() %14+ "")) {
                return each;
            }
        }
        throw new UnsupportedOperationException();
    }

    /**
     * in比较条件
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doInSharding(final Collection<String> availableTargetNames, final ShardingValue<Integer> shardingValue) {
        Collection<String> result = new LinkedHashSet<String>(availableTargetNames.size());
        Collection<Integer> values = shardingValue.getValues();
        for (Integer value : values) {
            for (String tableNames : availableTargetNames) {
                if (tableNames.endsWith(value % 14 + "")) {
                    result.add(tableNames);
                }
            }
        }
        return result;
    }

    /**
     * between比较条件
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doBetweenSharding(final Collection<String> availableTargetNames, final ShardingValue<Integer> shardingValue) {
        Collection<String> result = new LinkedHashSet<String>(availableTargetNames.size());
        Range<Integer> range = shardingValue.getValueRange();
        for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
            for (String each : availableTargetNames) {
                if (each.endsWith(i % 14+ "")) {
                    result.add(each);
                }
            }
        }
        return result;
    }
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值