Apache ShardingSphere 项目教程
1. 项目的目录结构及介绍
Apache ShardingSphere 是一个分布式数据库中间件平台,支持数据分片、读写分离、分布式事务等功能。项目的目录结构如下:
shardingsphere/
├── shardingsphere-agent/
├── shardingsphere-benchmarks/
├── shardingsphere-cdc/
├── shardingsphere-checkstyle/
├── shardingsphere-cli/
├── shardingsphere-cluster/
├── shardingsphere-distsql/
├── shardingsphere-doc/
├── shardingsphere-features/
├── shardingsphere-infra/
├── shardingsphere-jdbc/
├── shardingsphere-kernel/
├── shardingsphere-mode/
├── shardingsphere-parser/
├── shardingsphere-proxy/
├── shardingsphere-scaling/
├── shardingsphere-scenario/
├── shardingsphere-spi/
├── shardingsphere-sql-parser/
├── shardingsphere-test/
├── shardingsphere-ui/
├── shardingsphere-utils/
├── .gitignore
├── .gitmodules
├── .travis.yml
├── LICENSE
├── NOTICE
├── README.md
├── pom.xml
主要目录介绍
shardingsphere-jdbc/
: 提供 JDBC 接口的实现,适用于 Java 应用。shardingsphere-proxy/
: 提供一个静态入口,支持所有语言,适用于 OLAP 应用和数据库管理。shardingsphere-distsql/
: 提供分布式 SQL 支持。shardingsphere-doc/
: 包含项目的文档。shardingsphere-test/
: 包含测试代码。pom.xml
: Maven 项目配置文件。
2. 项目的启动文件介绍
shardingsphere-jdbc
启动 shardingsphere-jdbc
需要通过 Java 代码进行配置和初始化。以下是一个简单的示例:
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
public class ShardingSphereJdbcExample {
public static void main(String[] args) throws Exception {
File yamlFile = new File("config.yaml");
DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute("SELECT * FROM t_order");
}
}
}
shardingsphere-proxy
启动 shardingsphere-proxy
需要通过命令行进行。以下是一个示例:
bin/start.sh
3. 项目的配置文件介绍
shardingsphere-jdbc
配置文件通常是一个 YAML 文件,示例如下:
dataSources:
ds_0:
url: jdbc:mysql://localhost:3306/demo_ds_0?serverTimezone=UTC&useSSL=false
username: root
password: root
connectionTimeoutMilliseconds: 30000
idleTimeoutMilliseconds: 60000
maxLifetimeMilliseconds: 1800000
maxPoolSize: 50
rules:
- !SHARDING
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order_${0..1}
tableStrategy:
standard:
shardingColumn: order_id
shardingAlgorithmName: t_order_inline
keyGenerateStrategy:
column: order_id
keyGeneratorName: snowflake
shardingAlgorithms:
t_order_inline:
type: INLINE
props:
algorithm-expression: t_order_${order_id % 2}
keyGenerators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
shardingsphere-proxy
配置文件通常位于 conf
目录下,示例如下:
authentication:
users:
root:
password: root
sharding:
password: sharding
authorizedSche