Pārlūkot izejas kodu

content-service 引入 shardingsphere-jdbc:5.5.2 版本实现读写分离

reghao 4 mēneši atpakaļ
vecāks
revīzija
4b689eaa71

+ 8 - 3
content/content-service/pom.xml

@@ -80,6 +80,11 @@
             <artifactId>sharding-core-common</artifactId>
             <version>4.1.1</version>
         </dependency>-->
+        <dependency>
+            <groupId>org.apache.shardingsphere</groupId>
+            <artifactId>shardingsphere-jdbc</artifactId>
+            <version>5.5.2</version>
+        </dependency>
 
         <dependency>
             <groupId>org.springframework.boot</groupId>
@@ -178,7 +183,7 @@
             <version>1.7.0</version>
         </dependency>
 
-        <dependency>
+        <!--<dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-actuator</artifactId>
         </dependency>
@@ -189,7 +194,7 @@
         <dependency>
             <groupId>io.micrometer</groupId>
             <artifactId>micrometer-registry-prometheus</artifactId>
-        </dependency>
+        </dependency>-->
     </dependencies>
 
     <profiles>
@@ -231,9 +236,9 @@
                 <directory>src/main/resources</directory>
                 <filtering>true</filtering>
                 <includes>
-                    <!--<include>bootstrap.yml</include>-->
                     <include>application.yml</include>
                     <include>application-${profile.active}.yml</include>
+                    <include>sharding-${profile.active}.yml</include>
                     <include>mapper/**</include>
                     <include>*.xml</include>
                 </includes>

+ 3 - 3
content/content-service/src/main/java/cn/reghao/tnb/content/app/aop/DataSourceAspect.java

@@ -15,9 +15,9 @@ import org.springframework.stereotype.Component;
  * @date 2023-12-31 03:01:16
  */
 @Slf4j
-@Aspect
-@Component
-@EnableAspectJAutoProxy(proxyTargetClass = true)
+//@Aspect
+//@Component
+//@EnableAspectJAutoProxy(proxyTargetClass = true)
 public class DataSourceAspect {
     @Pointcut("execution(* cn.reghao.tnb.content.app.mall.db.mapper.*.*(..))")
     public void aspect() {

+ 7 - 7
content/content-service/src/main/java/cn/reghao/tnb/content/app/config/mybatis/DynamicDataSourceConfig.java

@@ -1,7 +1,7 @@
 package cn.reghao.tnb.content.app.config.mybatis;
 
 import cn.reghao.tnb.content.app.config.DataSourceType;
-//import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
+import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
@@ -15,18 +15,18 @@ import java.util.Map;
  */
 //@Configuration
 public class DynamicDataSourceConfig {
-    /*@Bean(name = "dynamicDataSource")
+    //@Bean(name = "dynamicDataSource")
     public DynamicDataSource dynamicDataSource(DataSource dataSource) throws Exception {
-        if (dataSource instanceof ShardingDataSource) {
-            ShardingDataSource shardingDataSource = (ShardingDataSource) dataSource;
-            Map<String, DataSource> map = shardingDataSource.getDataSourceMap();
+        if (dataSource instanceof ShardingSphereDataSource) {
+            ShardingSphereDataSource shardingDataSource = (ShardingSphereDataSource) dataSource;
+            /*Map<String, DataSource> map = shardingDataSource.getDataSourceMap();
             DataSource dataSourceMaster = map.get(DataSourceType.master.getName());
             DataSource dataSourceSlave = map.get(DataSourceType.slave.getName());
-            return getDynamicDataSource(dataSourceMaster, dataSourceSlave);
+            return getDynamicDataSource(dataSourceMaster, dataSourceSlave);*/
         }
 
         throw new Exception("DataSource is not ShardingDataSource");
-    }*/
+    }
 
     private DynamicDataSource getDynamicDataSource(DataSource master, DataSource slave) {
         Map<Object, Object> targetDataSources = new HashMap<>();

+ 1 - 1
content/content-service/src/main/java/cn/reghao/tnb/content/app/config/mybatis/SqlSessionConfig.java

@@ -71,7 +71,7 @@ public class SqlSessionConfig {
     }
 
     @Bean(name = "sqlSessionFactory")
-    public SqlSessionFactory sqlSessionFactory(/*@Qualifier("dynamicDataSource") */DataSource dataSource) throws Exception {
+    public SqlSessionFactory sqlSessionFactory(/*@Qualifier("dynamicDataSource")*/ DataSource dataSource) throws Exception {
         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
         factoryBean.setDataSource(dataSource);
         factoryBean.setPlugins(pageListInterceptor());

+ 0 - 17
content/content-service/src/main/java/cn/reghao/tnb/content/app/config/shard/ModuloShardingTableAlgorithm.java

@@ -1,17 +0,0 @@
-package cn.reghao.tnb.content.app.config.shard;
-
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
-
-import java.util.Collection;
-
-/**
- * @author reghao
- * @date 2022-03-15 21:01:01
- */
-public class ModuloShardingTableAlgorithm /*implements PreciseShardingAlgorithm<String>*/ {
-    /*@Override
-    public String doSharding(Collection<String> var1, PreciseShardingValue<String> var2) {
-        return "qq_mobile_$->{qq % 4}";
-    }*/
-}

+ 0 - 43
content/content-service/src/main/java/cn/reghao/tnb/content/app/config/shard/ShardingDataSourceConfig.java

@@ -1,43 +0,0 @@
-package cn.reghao.tnb.content.app.config.shard;
-
-//import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
-//import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
-//import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
-//import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
-
-import javax.sql.DataSource;
-import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * @author reghao
- * @date 2022-03-15 18:46:37
- */
-//@Configuration
-public class ShardingDataSourceConfig {
-    private final String database = "reghao_oss_rdb";
-
-    //@Bean
-    /*public DataSource getShardingDataSource() throws SQLException {
-        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
-        shardingRuleConfig.getTableRuleConfigs().add(getTableRuleConfiguration());
-        //shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("qq", "qq_mobile_$->{qq % 4}"));
-        shardingRuleConfig.setDefaultTableShardingStrategyConfig(
-                new StandardShardingStrategyConfiguration("qq", new ModuloShardingTableAlgorithm()));
-        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties());
-    }
-
-    private TableRuleConfiguration getTableRuleConfiguration() {
-        String logicalTalbe = "qq_mobile";
-        String actualDataNodes = database + ".qq_mobile_$->{0..3}";
-        return new TableRuleConfiguration(logicalTalbe, actualDataNodes);
-    }*/
-
-    private Map<String, DataSource> createDataSourceMap() {
-        Map<String, DataSource> result = new HashMap<>();
-        result.put(database, DataSourceUtil.createDataSource(database));
-        return result;
-    }
-}

+ 90 - 0
content/content-service/src/main/java/cn/reghao/tnb/content/app/config/shard/ShardingSphereConfig.java

@@ -0,0 +1,90 @@
+package cn.reghao.tnb.content.app.config.shard;
+
+import com.zaxxer.hikari.HikariDataSource;
+import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
+import org.apache.shardingsphere.infra.algorithm.core.config.AlgorithmConfiguration;
+import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
+import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;
+import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;
+import org.apache.shardingsphere.mode.repository.standalone.StandalonePersistRepositoryConfiguration;
+import org.apache.shardingsphere.readwritesplitting.config.ReadwriteSplittingRuleConfiguration;
+import org.apache.shardingsphere.readwritesplitting.config.rule.ReadwriteSplittingDataSourceGroupRuleConfiguration;
+import org.apache.shardingsphere.single.config.SingleRuleConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.sql.DataSource;
+import java.sql.SQLException;
+import java.util.*;
+
+/**
+ * resources/sharding.yml 配置文件的 Java API 版本
+ *
+ * @author reghao
+ * @date 2025-10-28 15:11:37
+ */
+//@Configuration
+public class ShardingSphereConfig {
+    @Bean
+    public DataSource getShardingDataSource() throws SQLException {
+        String databaseName = "readwrite_ds";
+        ModeConfiguration modeConfig = new ModeConfiguration("Standalone", new StandalonePersistRepositoryConfiguration("JDBC", new Properties()));
+        Map<String, DataSource> dataSourceMap = createDataSourceMap();
+
+        Collection<RuleConfiguration> ruleConfigs = new ArrayList<>();
+        SingleRuleConfiguration ruleConfig = new SingleRuleConfiguration();
+        ruleConfig.setTables(List.of("*.*"));
+        ruleConfigs.add(ruleConfig);
+
+        ReadwriteSplittingRuleConfiguration ruleConfig1 = getRuleConfig();
+        ruleConfigs.add(ruleConfig1);
+
+        Properties props = new Properties();
+        props.put(ConfigurationPropertyKey.SQL_SHOW.getKey(), false);
+        return ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig, dataSourceMap, ruleConfigs, props);
+    }
+
+    public ReadwriteSplittingRuleConfiguration getRuleConfig() {
+        ReadwriteSplittingDataSourceGroupRuleConfiguration dataSourceConfig =
+                new ReadwriteSplittingDataSourceGroupRuleConfiguration(
+                        "demo_read_query_ds",
+                        "write_ds",
+                        Arrays.asList("read_ds_0"),
+                        "demo_weight_lb");
+
+        Collection<ReadwriteSplittingDataSourceGroupRuleConfiguration> dataSourceGroups = new ArrayList<>();
+        dataSourceGroups.add(dataSourceConfig);
+
+        Properties algorithmProps = new Properties();
+        algorithmProps.setProperty("read_ds_0", "2");
+        //algorithmProps.setProperty("demo_read_ds_1", "1");
+        Map<String, AlgorithmConfiguration> loadBalancers = new HashMap<>(1);
+        loadBalancers.put("demo_weight_lb", new AlgorithmConfiguration("WEIGHT", algorithmProps));
+
+        ReadwriteSplittingRuleConfiguration ruleConfig = new ReadwriteSplittingRuleConfiguration(dataSourceGroups, loadBalancers);
+        return ruleConfig;
+    }
+
+    private Map<String, DataSource> createDataSourceMap() {
+        String jdbcUrl1 = "jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true";
+        String jdbcUrl2 = "jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true";
+
+        Map<String, DataSource> dataSourceMap = new HashMap<>();
+        // 配置第 1 个数据源
+        HikariDataSource dataSource1 = new HikariDataSource();
+        dataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
+        dataSource1.setJdbcUrl(jdbcUrl1);
+        dataSource1.setUsername("dev");
+        dataSource1.setPassword("Dev@123456");
+        dataSourceMap.put("write_ds", dataSource1);
+
+        // 配置第 2 个数据源
+        HikariDataSource dataSource2 = new HikariDataSource();
+        dataSource2.setDriverClassName("com.mysql.cj.jdbc.Driver");
+        dataSource2.setJdbcUrl(jdbcUrl2);
+        dataSource2.setUsername("dev");
+        dataSource2.setPassword("Dev@123456");
+        dataSourceMap.put("read_ds_0", dataSource2);
+        return dataSourceMap;
+    }
+}

+ 1 - 20
content/content-service/src/main/resources/application-cluster.yml

@@ -23,23 +23,4 @@ spring:
     addresses: 192.168.0.211:5672,192.168.0.212:5672,192.168.0.213:5672
     virtual-host: /
     username: test
-    password: Test@123456
-  shardingsphere:
-    datasource:
-      names: master,slave
-      masterslave:
-        name: ms
-        master-data-source-name: master
-        slave-data-source-names: slave
-      master:
-        type: com.zaxxer.hikari.HikariDataSource
-        driver-class-name: com.mysql.cj.jdbc.Driver
-        jdbc-url: jdbc:mysql://192.168.0.211/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-        username: test
-        password: Test@123456
-      slave:
-        type: com.zaxxer.hikari.HikariDataSource
-        driver-class-name: com.mysql.cj.jdbc.Driver
-        jdbc-url: jdbc:mysql://192.168.0.211/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-        username: test
-        password: Test@123456
+    password: Test@123456

+ 0 - 23
content/content-service/src/main/resources/application-dev.yml

@@ -26,29 +26,6 @@ spring:
     virtual-host: /
     username: dev
     password: Dev@123456
-  datasource:
-    url: jdbc:mysql://127.0.0.1/tnb_content_rdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-    username: dev
-    password: Dev@123456
-#  shardingsphere:
-#    datasource:
-#      names: master,slave
-#      masterslave:
-#        name: ms
-#        master-data-source-name: master
-#        slave-data-source-names: slave
-#      master:
-#        type: com.zaxxer.hikari.HikariDataSource
-#        driver-class-name: com.mysql.cj.jdbc.Driver
-#        jdbc-url: jdbc:mysql://127.0.0.1/tnb_content_rdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-#        username: dev
-#        password: Dev@123456
-#      slave:
-#        type: com.zaxxer.hikari.HikariDataSource
-#        driver-class-name: com.mysql.cj.jdbc.Driver
-#        jdbc-url: jdbc:mysql://127.0.0.1/tnb_content_rdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-#        username: dev
-#        password: Dev@123456
 eureka:
   client:
     service-url:

+ 0 - 19
content/content-service/src/main/resources/application-test.yml

@@ -24,25 +24,6 @@ spring:
     virtual-host: /
     username: test
     password: Test@123456
-  shardingsphere:
-    datasource:
-      names: master,slave
-      masterslave:
-        name: ms
-        master-data-source-name: master
-        slave-data-source-names: slave
-      master:
-        type: com.zaxxer.hikari.HikariDataSource
-        driver-class-name: com.mysql.cj.jdbc.Driver
-        jdbc-url: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-        username: test
-        password: Test@123456
-      slave:
-        type: com.zaxxer.hikari.HikariDataSource
-        driver-class-name: com.mysql.cj.jdbc.Driver
-        jdbc-url: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
-        username: test
-        password: Test@123456
 eureka:
   client:
     service-url:

+ 2 - 11
content/content-service/src/main/resources/application.yml

@@ -19,17 +19,8 @@ spring:
   profiles:
     active: @profile.active@
   datasource:
-    driver-class-name: com.mysql.cj.jdbc.Driver
-    type: com.zaxxer.hikari.HikariDataSource
-    hikari:
-      minimum-idle: 5
-      maximum-pool-size: 10
-      auto-commit: true
-      idle-timeout: 30000
-      pool-name: EvaluationHikariCP
-      max-lifetime: 1800000
-      connection-timeout: 30000
-      connection-test-query: SELECT 1
+    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
+    url: jdbc:shardingsphere:classpath:sharding-${spring.profiles.active}.yml
   cloud:
     inetutils:
       ignored-interfaces:

+ 48 - 0
content/content-service/src/main/resources/sharding-cluster.yml

@@ -0,0 +1,48 @@
+# 表明使用单机模式
+#https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/mode/
+mode:
+  type: Standalone
+  repository:
+    type: JDBC
+# 配置数据源
+# https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/data-source/
+dataSources:
+  # 配置主数据库(master3307可以写自己的名字)
+  master3307:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
+    username: test
+    password: Test@123456
+  # 配置从数据库(salve3308可以写自己的名字)
+  slave3308:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
+    username: test
+    password: Test@123456
+# 配置规则
+rules:
+  # 单表规则用于指定哪些单表需要被 ShardingSphere 管理,也可设置默认的单表数据源。
+  - !SINGLE
+    tables:
+      - "*.*" # 加载全部单表
+  #    defaultDataSource: master3307 # 默认数据源,仅在执行 CREATE TABLE 创建单表时有效。缺失值为空,表示随机单播路由。
+  # 声明使用读写分离规则
+  # https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/rules/readwrite-splitting/
+  - !READWRITE_SPLITTING
+    dataSourceGroups:
+      readwrite_ds: #读写分离逻辑数据源名称
+        writeDataSourceName: master3307  #写库数据源名称
+        readDataSourceNames: #读库数据源名称
+          - slave3308
+        transactionalReadQueryStrategy: PRIMARY # 事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)。默认值:DYNAMIC
+        loadBalancerName: round-robin # 负载均衡算法名称
+    # 负载均衡算法配置
+    loadBalancers:
+      round-robin: # 负载均衡算法名称
+        type: ROUND_ROBIN # 负载均衡算法类型
+# 属性配置
+props:
+  # 是否显示执行的SQL语句
+  sql-show: false

+ 48 - 0
content/content-service/src/main/resources/sharding-dev.yml

@@ -0,0 +1,48 @@
+# 表明使用单机模式
+#https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/mode/
+mode:
+  type: Standalone
+  repository:
+    type: JDBC
+# 配置数据源
+# https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/data-source/
+dataSources:
+  # 配置主数据库(master3307可以写自己的名字)
+  master3307:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
+    username: dev
+    password: Dev@123456
+  # 配置从数据库(salve3308可以写自己的名字)
+  slave3308:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
+    username: dev
+    password: Dev@123456
+# 配置规则
+rules:
+  # 单表规则用于指定哪些单表需要被 ShardingSphere 管理,也可设置默认的单表数据源。
+  - !SINGLE
+    tables:
+      - "*.*" # 加载全部单表
+  #    defaultDataSource: master3307 # 默认数据源,仅在执行 CREATE TABLE 创建单表时有效。缺失值为空,表示随机单播路由。
+  # 声明使用读写分离规则
+  # https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/rules/readwrite-splitting/
+  - !READWRITE_SPLITTING
+    dataSourceGroups:
+      readwrite_ds: #读写分离逻辑数据源名称
+        writeDataSourceName: master3307  #写库数据源名称
+        readDataSourceNames: #读库数据源名称
+          - slave3308
+        transactionalReadQueryStrategy: PRIMARY # 事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)。默认值:DYNAMIC
+        loadBalancerName: round-robin # 负载均衡算法名称
+    # 负载均衡算法配置
+    loadBalancers:
+      round-robin: # 负载均衡算法名称
+        type: ROUND_ROBIN # 负载均衡算法类型
+# 属性配置
+props:
+  # 是否显示执行的SQL语句
+  sql-show: true

+ 48 - 0
content/content-service/src/main/resources/sharding-test.yml

@@ -0,0 +1,48 @@
+# 表明使用单机模式
+#https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/mode/
+mode:
+  type: Standalone
+  repository:
+    type: JDBC
+# 配置数据源
+# https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/data-source/
+dataSources:
+  # 配置主数据库(master3307可以写自己的名字)
+  master3307:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
+    username: test
+    password: Test@123456
+  # 配置从数据库(salve3308可以写自己的名字)
+  slave3308:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://192.168.0.209/tnb_content_tdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
+    username: test
+    password: Test@123456
+# 配置规则
+rules:
+  # 单表规则用于指定哪些单表需要被 ShardingSphere 管理,也可设置默认的单表数据源。
+  - !SINGLE
+    tables:
+      - "*.*" # 加载全部单表
+  #    defaultDataSource: master3307 # 默认数据源,仅在执行 CREATE TABLE 创建单表时有效。缺失值为空,表示随机单播路由。
+  # 声明使用读写分离规则
+  # https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/rules/readwrite-splitting/
+  - !READWRITE_SPLITTING
+    dataSourceGroups:
+      readwrite_ds: #读写分离逻辑数据源名称
+        writeDataSourceName: master3307  #写库数据源名称
+        readDataSourceNames: #读库数据源名称
+          - slave3308
+        transactionalReadQueryStrategy: PRIMARY # 事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)。默认值:DYNAMIC
+        loadBalancerName: round-robin # 负载均衡算法名称
+    # 负载均衡算法配置
+    loadBalancers:
+      round-robin: # 负载均衡算法名称
+        type: ROUND_ROBIN # 负载均衡算法类型
+# 属性配置
+props:
+  # 是否显示执行的SQL语句
+  sql-show: false

+ 74 - 0
content/content-service/src/main/resources/sharding1.yml

@@ -0,0 +1,74 @@
+# 表明使用单机模式
+#https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/mode/
+mode:
+  type: Standalone
+  repository:
+    type: JDBC
+# 配置数据源
+# https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/data-source/
+dataSources:
+  # 配置主数据库(master3307可以写自己的名字)
+  master3307:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
+    username: dev
+    password: Dev@123456
+  # 配置从数据库(salve3308可以写自己的名字)
+  slave3308:
+    driverClassName: com.mysql.cj.jdbc.Driver
+    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    jdbcUrl: jdbc:mysql://localhost:3306/tnb_content_rdb?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
+    username: dev
+    password: Dev@123456
+# 配置规则
+rules:
+  # 单表规则用于指定哪些单表需要被 ShardingSphere 管理,也可设置默认的单表数据源。
+  - !SINGLE
+    tables:
+      - "*.*" # 加载全部单表
+  #    defaultDataSource: master3307 # 默认数据源,仅在执行 CREATE TABLE 创建单表时有效。缺失值为空,表示随机单播路由。
+  # 声明使用读写分离规则
+  # https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/rules/readwrite-splitting/
+  - !READWRITE_SPLITTING
+    dataSourceGroups:
+      readwrite_ds: #读写分离逻辑数据源名称
+        writeDataSourceName: master3307  #写库数据源名称
+        readDataSourceNames: #读库数据源名称
+          - slave3308
+        transactionalReadQueryStrategy: PRIMARY # 事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)。默认值:DYNAMIC
+        loadBalancerName: round-robin # 负载均衡算法名称
+    # 负载均衡算法配置
+    loadBalancers:
+      round-robin: # 负载均衡算法名称
+        type: ROUND_ROBIN # 负载均衡算法类型
+  # 分表路由配置
+  # https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/yaml-config/rules/sharding/
+  - !SHARDING
+    tables:
+      user: #逻辑表名
+        actualDataNodes: master3307.user_${0..1} #数据源名.表名(此处我的数据库有user_0, user1两张表)
+        tableStrategy: #分表策略  databaseStrategy:分库策略
+          standard: # 用于单分片键的标准分片场景 complex:用于多分片键的复合分片场景
+            shardingColumn: id # 分片列名称(此处按id分片)
+            shardingAlgorithmName: user_inline # 分片算法名称
+        keyGenerateStrategy: # 分布式序列策略
+          column: id  # 自增列名称,缺省表示不使用自增主键生成器
+          keyGeneratorName: snowflake # 分布式序列算法名称
+    # 定义分片算法
+    shardingAlgorithms:
+      user_inline: # 分片算法名称
+        # 分片算法类型
+        type: INLINE
+        # 分片算法的属性配置
+        props:
+          algorithm-expression: user_${id % 2}  # 分片算法表达式,根据id字段的值进行取模运算
+    # 定义键生成器
+    keyGenerators:
+      snowflake: # 分布式序列算法名称
+        # 键生成器类型
+        type: SNOWFLAKE
+# 属性配置
+props:
+  # 是否显示执行的SQL语句
+  sql-show: true