<mark>此插件，主要社区贡献人（Sorghum）</mark>

```xml
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon-data-shardingds</artifactId>
</dependency>
```

#### 1、描述

数据扩展插件，基于 Apache ShardingSphere v5.x 封装（[代码仓库](https://github.com/apache/shardingsphere)），为 Solon Data 提供了 **分片数据源** 的能力扩展。<mark>（v2.3.1 之后支持）</mark>

分片数据源，常见的合适场景：

* 分库分表数据架构
* 读写分离数据架构

提醒：更多的使用场景及方式，参考官网资料。

#### 2、配置示例

配置分格有两种：1，将配置内容独立为一个文件；2，将配置做为主配置的内容（注意 "|" 符号）。这个新手配置起来挺麻烦的，具体的配置内容，参考官网：[https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/](https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/)

```yaml
# 模式一:: 支持：外置sharding.yml的配置
demo.db1:
  file: "classpath:sharding.yml"
  
# 模式二:: 支持：内置sharding.yml的配置
demo.db2:
  config: |
      mode:
        type: Standalone
        repository:
          type: JDBC
      dataSources:
        ds_1:
          dataSourceClassName: com.zaxxer.hikari.HikariDataSource
          driverClassName: com.mysql.jdbc.Driver
          jdbcUrl: jdbc:mysql://localhost:3306/xxxxxxx
          username: root
          password: xxxxxxx
        ds_2:
          dataSourceClassName: com.zaxxer.hikari.HikariDataSource
          driverClassName: com.mysql.jdbc.Driver
          jdbcUrl: jdbc:mysql://localhost:3306/xxxxxxx
          username: root
          password: xxxxxxx
      rules:
        - !READWRITE_SPLITTING
          dataSources:
            readwrite_ds:
              staticStrategy:
                writeDataSourceName: ds_1
                readDataSourceNames:
                  - ds_2
              loadBalancerName: random
          loadBalancers:
            random:
              type: RANDOM
      props:
        sql-show: true
```

注意：使用 ShardingSphere 表达式时，不要使用`${}`，改用`$->{}` <mark>（这是 ShardingSphere 专用表达式）</mark>

#### 3、应用示例

配置好后，与别的数据源 bean 创建方式无异。与已适配的 orm 框架协作时，也自为自然。

```java
//配置数据源 bean
@Configuration
public class Config {
    @Bean(name = "db1", typed = true)
    public DataSource db1(@Inject("${demo.db1}") ShardingDataSource ds) throws Exception {
        return ds;
    }

    @Bean(name = "db2")
    public DataSource db2(@Inject("${demo.db2}") ShardingDataSource ds) throws Exception {
        return ds;
    }
}

@Component
public class UserService{
    @Db("db1")
    OrderMapper orderMapper;
    
    @Db("db2")
    UserMapper userMapper;
    
    public void addUser(){
        userMapper.inserUser();
    }
    
    public void getUserList(){
        userMapper.selectUserList();
    }
}
```

#### 4、参考示例

[https://gitee.com/noear/solon-examples/tree/main/4.Solon-Data/demo4003-shardingds](https://gitee.com/noear/solon-examples/tree/main/4.Solon-Data/demo4003-shardingds)



