Sharding-jdbc

Sharding-jdbc依賴

          <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>sharding-jdbc-config-common</artifactId>
            <version>1.5.4.1</version>
        </dependency>

1.配置多數(shù)據(jù)源

public DataSource datasource1(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/sharding");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        return druidDataSource;
    }
    
    public DataSource datasource2(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/sharding1");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        return druidDataSource;
    }

2.配置mybatis

private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
    
    @Autowired
    XbDataSource xbDataSource;
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setDataSource(xbDataSource.getShardingDataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("limouchao.entity");
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            logger.error("sqlSessionFactory create bean fail", e);
            return null;
        }
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(xbDataSource.getShardingDataSource());
    }

3.配置Sharding-jdbc數(shù)據(jù)源

private DataSource shardingDataSource;
    
    
    @PostConstruct
    public void init(){
         HashMap<String, DataSource> map = new HashMap<>();
         DatasourceConfig datasourceConfig=new DatasourceConfig();
         map.put("dataSource0", datasourceConfig.datasource1());
         map.put("dataSource1", datasourceConfig.datasource2());
         DataSourceRule dataSourceRule =new DataSourceRule(map);
         List<String> pList = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                pList.add("user" + i);
            }
         List<TableRule> tableRuleList = new ArrayList<>();
         tableRuleList.add(new TableRule.TableRuleBuilder("user")
                    .actualTables(pList)
                    .dataSourceRule(dataSourceRule)
                    .tableShardingStrategy(new TableShardingStrategy("id",new ProgramShardingAlgorithm())).databaseShardingStrategy(new DatabaseShardingStrategy("id", new ProgramDataBaseAlgorithm())).build());//.databaseShardingStrategy(new DatabaseShardingStrategy("id", new ProgramDataBaseAlgorithm()))
         ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(tableRuleList).build();
         try {
            shardingDataSource = ShardingDataSourceFactory.createDataSource(shardingRule);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public DataSource getShardingDataSource() {
        return shardingDataSource;
    }

4.實現(xiàn)分表分庫策略

1.分表策略實現(xiàn)SingleKeyTableShardingAlgorithm

@Component
public class ProgramShardingAlgorithm implements SingleKeyTableShardingAlgorithm<String>{

    @Override
    public String doEqualSharding(Collection<String> availableTargetNames,
            ShardingValue<String> shardingValue) {
         for (String each : availableTargetNames) {
             //判斷值是否在設(shè)計表中的哪一個。判斷string的后綴是否為。。。
//              if (each.endsWith(shardingValue.getValue()%4+"")) {
//                  return each;
//              }
             
             if(each.endsWith(Math.abs(shardingValue.getValue().hashCode())%4+"")){
                 return each;
             }
            }
            throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doInSharding(Collection<String> availableTargetNames,
            ShardingValue<String> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        Collection<String> values = shardingValue.getValues();
        for (String value : values) {
            for (String tableNames : availableTargetNames) {
                if (tableNames.endsWith(value.hashCode()%4+"")) {
                    result.add(tableNames);
                }
            }
        }
        return result;
    }

    @Override
    public Collection<String> doBetweenSharding(Collection<String> availableTargetNames,
            ShardingValue<String> shardingValue) {
        return null;
//      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 % 4+ "")) {
//                    result.add(each);
//                }
//            }
//        }
//        return result;
    }

}

2.分庫實現(xiàn)SingleKeyDatabaseShardingAlgorithm

public class ProgramDataBaseAlgorithm implements SingleKeyDatabaseShardingAlgorithm<String>{

    @Override
    public String doEqualSharding(Collection<String> availableTargetNames, ShardingValue<String> shardingValue) {
        for (String each : availableTargetNames) {  
            if (each.endsWith((Math.abs(shardingValue.getValue().hashCode())%2) + "")) { 
                
                return each;  
            }  
        }  
        throw new IllegalArgumentException(); 
    }

    @Override
    public Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<String> shardingValue) {
         Collection<String> result = new LinkedHashSet<String>(availableTargetNames.size());  
            for (String value : shardingValue.getValues()) {  
                for (String tableName : availableTargetNames) {  
                    if (tableName.endsWith((Math.abs(value.hashCode())) % 2 + "")) {
                        System.out.println(value.hashCode()+"======"+Math.abs(value.hashCode())% 2);
                        result.add(tableName);  
                    }  
                }  
            }  
            return result; 
    }

    @Override
    public Collection<String> doBetweenSharding(Collection<String> availableTargetNames, ShardingValue<String> shardingValue) {
//      Collection<String> result = new LinkedHashSet<String>(availableTargetNames.size());  
//        Range<String> range = (Range<String>) shardingValue.getValueRange();  
//        for (String i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {  
//            for (String each : availableTargetNames) {  
//                if (each.endsWith(i % 4 + "")) {  
//                    result.add(each);  
//                }  
//            }  
//        }  
//        return result;  
        return null;
    }
}

參考url

https://www.cnblogs.com/zwt1990/p/6762135.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,246評論 0 4
  • 阿飛Javaer,轉(zhuǎn)載請注明原創(chuàng)出處,謝謝! sharding-jdbc源碼分析準(zhǔn)備工作 接下來對sharding...
    阿飛的博客閱讀 3,175評論 1 9
  • R 原文片段 每個階段企業(yè)組織變革 I 總結(jié)思考 最近在朋友圈看旅行青蛙特別風(fēng)靡,自己下載了一個,養(yǎng)了幾天,很輕的...
    山言良語lynn閱讀 210評論 0 0
  • 在這個鮮肉橫行,美顏肆虐的社會,你很容易迷戀上一個偶像,這些盛世美顏總會在某個瞬間虜獲你的心。來的快去的也快,很快...
    她愛她閱讀 209評論 1 0
  • 故鄉(xiāng)有我的痕跡 拂去厚厚的塵土 沒有色彩 仍有溫度 ——余剛《遠(yuǎn)去的故鄉(xiāng)》 去年: 母親微笑著,調(diào)侃式地問我,不是...
    小雅愛說話閱讀 365評論 0 2

友情鏈接更多精彩內(nèi)容