Sharding-jdbc

Sharding-jdbc依赖

          
            com.dangdang
            sharding-jdbc-config-common
            1.5.4.1
        

1.配置多数据源

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数据源

private DataSource shardingDataSource;
    
    
    @PostConstruct
    public void init(){
         HashMap map = new HashMap<>();
         DatasourceConfig datasourceConfig=new DatasourceConfig();
         map.put("dataSource0", datasourceConfig.datasource1());
         map.put("dataSource1", datasourceConfig.datasource2());
         DataSourceRule dataSourceRule =new DataSourceRule(map);
         List pList = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                pList.add("user" + i);
            }
         List 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.实现分表分库策略

1.分表策略实现SingleKeyTableShardingAlgorithm

@Component
public class ProgramShardingAlgorithm implements SingleKeyTableShardingAlgorithm{

    @Override
    public String doEqualSharding(Collection availableTargetNames,
            ShardingValue shardingValue) {
         for (String each : availableTargetNames) {
             //判断值是否在设计表中的哪一个。判断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 doInSharding(Collection availableTargetNames,
            ShardingValue shardingValue) {
        Collection result = new LinkedHashSet<>(availableTargetNames.size());
        Collection 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 doBetweenSharding(Collection availableTargetNames,
            ShardingValue shardingValue) {
        return null;
//      Collection result = new LinkedHashSet(availableTargetNames.size());
//        Range 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.分库实现SingleKeyDatabaseShardingAlgorithm

public class ProgramDataBaseAlgorithm implements SingleKeyDatabaseShardingAlgorithm{

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

    @Override
    public Collection doInSharding(Collection availableTargetNames, ShardingValue shardingValue) {
         Collection result = new LinkedHashSet(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 doBetweenSharding(Collection availableTargetNames, ShardingValue shardingValue) {
//      Collection result = new LinkedHashSet(availableTargetNames.size());  
//        Range range = (Range) 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

你可能感兴趣的:(Sharding-jdbc)