ShardingJdbc2.X學習總結系列(二):使用

1.maven 引入依賴jar包

<dependency>
     <groupId>io.shardingjdbc</groupId>
     <artifactId>sharding-jdbc-core</artifactId>
     <version>2.0.3</version>
</dependency>

2.配置數據源信息

databasesString=[{"name": "shading_jdbc1",\
  "url": "jdbc:mysql://localhost:3306/shading_jdbc1?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true",\
  "username": "root",\
  "password": "root",\
  "driverClassName": "com.mysql.jdbc.Driver",\
  "initialSize": "5",\
  "minIdle": "5",\
  "maxActive": "20",\
  "maxWait": "60000",\
  "validationQuery": "SELECT 1 FROM DUAL",\
  "testOnBorrow": "false",\
  "testOnReturn": "false",\
  "testWhileIdle": "true",\
  "timeBetweenEvictionRunsMillis": "60000",\
  "minEvictableIdleTimeMillis": "300000",\
  "filters": [\
  "stat",\
  "log4j"\
  ]\
  },\
  {\
  "name": "shading_jdbc2",\
  "url": "jdbc:mysql://localhost:3306/shading_jdbc2?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true",\
  "username": "root",\
  "password": "root",\
  "driverClassName": "com.mysql.jdbc.Driver",\
  "initialSize": "5",\
  "minIdle": "5",\
  "maxActive": "20",\
  "maxWait": "60000",\
  "validationQuery": "SELECT 1 FROM DUAL",\
  "testOnBorrow": "false",\
  "testOnReturn": "false",\
  "testWhileIdle": "true",\
  "timeBetweenEvictionRunsMillis": "60000",\
  "minEvictableIdleTimeMillis": "300000",\
  "filters": [\
  "stat",\
  "log4j"\
  ]\
  }\
  ]
tableString=shading_jdbc1.user1,shading_jdbc1.user2,shading_jdbc2.user1,shading_jdbc2.user2
    //這裏是配置的數據源信息
    @Value("${databasesString}")
    protected String databasesString;
    
    //這裏是分表的信息
    @Value("#{'${tableString}'.split(',')}")
    protected List<String> tableString;

    @Bean
    public Map<String, DataSource> dataSourceMap() {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        if (StringUtils.isEmpty(databasesString)){
            log.error("數據庫database配置數據爲空,請查看配置參數:databasesString");
            throw new BizException(-1L,"數據庫database配置數據爲空");
        }
        try {
            List<DataSourceShading> databases = new Gson().fromJson(databasesString,
                    new TypeToken<List<DataSourceShading>>(){}.getType());
            for (DataSourceShading dataSourceShading : databases) {
                DruidDataSource dataSource = new DruidDataSource();
                BeanUtils.copyProperties(dataSourceShading,dataSource);
                dataSourceMap.put(dataSourceShading.getName(), dataSource);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("數據庫database配置數據異常,請查看配置參數:databasesString :{},error:{}",databasesString,e.getMessage(),e);
            throw new BizException(-1L,"數據庫database配置數據異常");
        }
        return dataSourceMap;
    }

    @Bean("shardingDataSource")
    public DataSource shardingDataSource(HashMap<String, DataSource> dataSourceMap) throws SQLException{
        //數據庫shading策略
        StandardShardingStrategy databaseShardingStrategy = new StandardShardingStrategy("user_id", new DataSourceShardingAlgorithm());
        //數據表shading策略
        StandardShardingStrategy tableShardingStrategy = new StandardShardingStrategy("user_id", new TableShardingAlgorithm());
        //單個表的分庫分表規則配置
        TableRule userTableRule = new TableRule("user",tableString,dataSourceMap,databaseShardingStrategy,tableShardingStrategy,null,null,null);
        //整體的分庫分表規則配置
        ShardingRule shardingRule = new ShardingRule(dataSourceMap,"shading_jdbc1", Lists.<TableRule>newArrayList(userTableRule),databaseShardingStrategy,tableShardingStrategy,null);
        return new ShardingDataSource(shardingRule);
    }

3.實現分庫分表策略

    private long getIndex(long id, int size) {
        return (id & (size - 1)) + 1;
    }

    /**
     * 根據分片值和SQL的=運算符計算分片結果名稱集合.
     *
     * @param availableTargetNames 所有的可用目標名稱集合, 一般是數據源
     * @param preciseShardingValue        分片值  也就是分片規則的字段值
     *
     * @return 分片後指向的目標名稱, 一般是數據源或表名稱
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        long index = getIndex(preciseShardingValue.getValue(),availableTargetNames.size());
        for (String targetName : availableTargetNames) {
            if (targetName.endsWith(index+"")) {
                log.debug("the target database name: {}", targetName);
                return targetName;
            }
        }
        throw new UnsupportedOperationException();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章