侧边栏壁纸
博主头像
码森林博主等级

一起走进码森林,享受编程的乐趣,发现科技的魅力,创造智能的未来!

  • 累计撰写 146 篇文章
  • 累计创建 74 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

ShardingSphere4.1.1 | Sharding-JDBC配置中心

码森林
2022-11-15 / 0 评论 / 0 点赞 / 536 阅读 / 4,521 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-11-15,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

编排治理

编排治理模块提供配置中心/注册中心(以及规划中的元数据中心)、配置动态化、数据库熔断禁用、调用链路等治理能力。

1、配置中心的实现动机:

  • 配置集中化:越来越多的运行时实例,使得散落的配置难于管理,配置不同步导致的问题十分严重。将配置集中于配置中心,可以更加有效进行管理。
  • 配置动态化:配置修改后的分发,是配置中心可以提供的另一个重要能力。它可支持数据源、表与分片及读写分离策略的动态切换。

2、注册中心的实现动机:

  • 相对于配置中心管理配置数据,注册中心存放运行时的动态/临时状态数据,比如可用的proxy的实例,需要禁用或熔断的datasource实例。
  • 通过注册中心,可以提供熔断数据库访问程序对数据库的访问和禁用从库的访问的编排治理能力。治理仍然有大量未完成的功能(比如流控等)。

3、支持的配置中心/注册中心

SPI

Service Provider Interface (SPI)是一种为了被第三方实现或扩展的API。它可以用于实现框架扩展或组件替换。

ShardingSphere在数据库治理模块使用SPI方式载入数据到配置中心/注册中心,进行实例熔断和数据库禁用。 目前,ShardingSphere内部支持Zookeeper和etcd这种常用的配置中心/注册中心。 此外,您可以使用其他第三方配置中心/注册中心,并通过SPI的方式注入到ShardingSphere,从而使用该配置中心/注册中心,实现数据库治理功能。

Zookeeper

ShardingSphere官方使用Apache Curator作为Zookeeper的实现方案(支持配置中心和注册中心)。 请使用Zookeeper 3.4.6及其以上版本,详情请参见官方网站

Etcd

ShardingSphere官方使用io.etcd/jetcd作为Etcd的实现方案(支持配置中心和注册中心)。 请使用Etcd v3以上版本,详情请参见官方网站

Apollo

ShardingSphere官方使用Apollo Client作为Apollo的实现方案(支持配置中心)。 请使用Apollo Client 1.5.0及其以上版本,详情请参见官方网站

Nacos

ShardingSphere官方使用Nacos Client作为Nacos的实现方案(支持配置中心)。 请使用Nacos Client 1.0.0及其以上版本,详情请参见官方网站

其他

使用SPI方式自行实现相关逻辑编码。

使用Zookeeper实现配置中心

Zookeeper 相关:

0、目标

  • orchestration的属性overwrite设置为true会覆盖配置中心的配置
  • 验证配置中心修改配置对项目立即生效,以打印sql属性为例

1、项目构建

创建一个SpringBoot项目,引入依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>cn.zwqh</groupId>
        <artifactId>sharding-sphere-4.1.1</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.zwqh</groupId>
    <artifactId>sharding-sphere-demo-7</artifactId>
    <version>${parent.version}</version>

    <packaging>jar</packaging>

    <name>sharding-sphere-demo-7</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>


        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- 如果使用sp-distributed 服务治理环境,需引入该依赖,并关闭sharding-jdbc-spring-boot-starter的依赖-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-orchestration-spring-boot-starter</artifactId>
        </dependency>

        <!-- 如果使用sp-distributed 服务治理环境,且使用zookeeper作为配置或注册中心,需引入该依赖,并关闭sharding-jdbc-spring-boot-starter的依赖-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-orchestration-center-zookeeper-curator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>cn.zwqh.shardingspheredemo7.ShardingSphereDemo7Application</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2、SQL创建脚本

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_address
-- ----------------------------
DROP TABLE IF EXISTS `t_address`;
CREATE TABLE `t_address` (
  `address_id` bigint NOT NULL COMMENT '地址id',
  `address_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`address_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- ----------------------------
-- Table structure for t_order_0
-- ----------------------------
DROP TABLE IF EXISTS `t_order_0`;
CREATE TABLE `t_order_0` (
  `order_id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL,
  `address_id` bigint NOT NULL,
  `status` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=622395693008420866 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- ----------------------------
-- Table structure for t_order_1
-- ----------------------------
DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1` (
  `order_id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL,
  `address_id` bigint NOT NULL,
  `status` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=622395693725646849 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- ----------------------------
-- Table structure for t_order_item_0
-- ----------------------------
DROP TABLE IF EXISTS `t_order_item_0`;
CREATE TABLE `t_order_item_0` (
  `order_item_id` bigint NOT NULL AUTO_INCREMENT,
  `order_id` bigint NOT NULL,
  `user_id` int NOT NULL,
  `status` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`order_item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- ----------------------------
-- Table structure for t_order_item_1
-- ----------------------------
DROP TABLE IF EXISTS `t_order_item_1`;
CREATE TABLE `t_order_item_1` (
  `order_item_id` bigint NOT NULL AUTO_INCREMENT,
  `order_id` bigint NOT NULL,
  `user_id` int NOT NULL,
  `status` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`order_item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

SET FOREIGN_KEY_CHECKS = 1;

3、配置文件

# 应用名称
spring.application.name=sharding-sphere-demo-7

spring.shardingsphere.datasource.names=ds0,ds1

spring.shardingsphere.datasource.ds0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds0.jdbc-url=jdbc:mysql://127.0.0.1:3306/sharding_sphere_0
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456
spring.shardingsphere.datasource.ds0.max-active=16

spring.shardingsphere.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds1.jdbc-url=jdbc:mysql://127.0.0.1:3306/sharding_sphere_1
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456
spring.shardingsphere.datasource.ds1.max-active=16

spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds$->{user_id % 2}

spring.shardingsphere.sharding.binding-tables=t_order,t_order_item
spring.shardingsphere.sharding.default-datasource-name=ds0
spring.shardingsphere.sharding.broadcast-tables=t_address

spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order_$->{0..1}
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.props.worker.id=123

spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds$->{0..1}.t_order_item_$->{0..1}
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order_item.key-generator.props.worker.id=123

spring.shardingsphere.props.sql.show=true


#需要的编排类型
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.orchestration-type=registry_center,config_center
#配置中心类型。如:zookeeper
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.instance-type=zookeeper
#连接注册中心服务器的列表。包括IP地址和端口号。多个地址用逗号分隔。如: host1:2181,host2:2181
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.server-lists=192.168.20.56:2181
#注册中心的命名空间
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.namespace=orchestration-spring-boot-demo
#本地配置是否覆盖注册中心配置。如果可覆盖,每次启动都以本地配置为准
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.props.overwrite=true

4、实体类

@Data
public class Address {
    
    private Long addressId;
    
    private String addressName;
}

@Data
public class Order {

    private long orderId;

    private int userId;

    private long addressId;

    private String status;
}

@Data
public class OrderItem{
    
    private long orderItemId;
    
    private long orderId;
    
    private int userId;
    
    private String status;

}

5、验证:项目启动本地配置覆盖配置中心

[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 17] ls /
----------------------------------------------------------------------------------------------------
[acl_test, persistent_node, zookeeper]
# 未启动项目时,无项目相关节点

启动项目

![image-20210723105456385](/Users/charlie/Library/Application Support/typora-user-images/image-20210723105456385.png)

[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 18] ls /
----------------------------------------------------------------------------------------------------
[acl_test, orchestration-spring-boot-demo, persistent_node, zookeeper]

[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 19] ls -R /orchestration-spring-boot-demo
----------------------------------------------------------------------------------------------------
/orchestration-spring-boot-demo
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/state
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/props
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema/logic_db
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema/logic_db/datasource
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema/logic_db/rule
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/state/datasources
/orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/state/instances

# 相对于sharding-sphere配置里面的Sharding Properties。
[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 20] get /orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/props
----------------------------------------------------------------------------------------------------
sql.show: 'true'

# 多个数据库连接池的集合,不同数据库连接池属性自适配
[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 21] get /orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema/logic_db/datasource
----------------------------------------------------------------------------------------------------
ds0: !!org.apache.shardingsphere.orchestration.core.configuration.YamlDataSourceConfiguration
  dataSourceClassName: com.zaxxer.hikari.HikariDataSource
  properties:
    password: '123456'
    dataSourceJNDI: null
    transactionIsolation: null
    connectionTestQuery: null
    driverClassName: com.mysql.jdbc.Driver
    initializationFailTimeout: 1
    jdbcUrl: jdbc:mysql://127.0.0.1:3306/sharding_sphere_0
    minimumIdle: 10
    maxLifetime: 1800000
    maximumPoolSize: 10
    schema: null
    validationTimeout: 5000
    dataSourceClassName: null
    connectionTimeout: 30000
    idleTimeout: 600000
    exceptionOverrideClassName: null
    leakDetectionThreshold: 0
    connectionInitSql: null
    poolName: HikariPool-1
    catalog: null
    username: root
ds1: !!org.apache.shardingsphere.orchestration.core.configuration.YamlDataSourceConfiguration
  dataSourceClassName: com.zaxxer.hikari.HikariDataSource
  properties:
    password: '123456'
    dataSourceJNDI: null
    transactionIsolation: null
    connectionTestQuery: null
    driverClassName: com.mysql.jdbc.Driver
    initializationFailTimeout: 1
    jdbcUrl: jdbc:mysql://127.0.0.1:3306/sharding_sphere_1
    minimumIdle: 10
    maxLifetime: 1800000
    maximumPoolSize: 10
    schema: null
    validationTimeout: 5000
    dataSourceClassName: null
    connectionTimeout: 30000
    idleTimeout: 600000
    exceptionOverrideClassName: null
    leakDetectionThreshold: 0
    connectionInitSql: null
    poolName: HikariPool-2
    catalog: null
    username: root

# 数据分片配置,包括数据分片配置
[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 22] get /orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/schema/logic_db/rule
----------------------------------------------------------------------------------------------------
bindingTables:
- t_order
- t_order_item
broadcastTables:
- t_address
defaultDataSourceName: ds0
defaultDatabaseStrategy:
  inline:
    algorithmExpression: ds$->{user_id % 2}
    shardingColumn: user_id
tables:
  t_order:
    actualDataNodes: ds$->{0..1}.t_order_$->{0..1}
    keyGenerator:
      column: order_id
      props:
        worker.id: '123'
      type: SNOWFLAKE
    logicTable: t_order
    tableStrategy:
      inline:
        algorithmExpression: t_order_$->{order_id % 2}
        shardingColumn: order_id
  t_order_item:
    actualDataNodes: ds$->{0..1}.t_order_item_$->{0..1}
    keyGenerator:
      column: order_item_id
      props:
        worker.id: '123'
      type: SNOWFLAKE
    logicTable: t_order_item
    tableStrategy:
      inline:
        algorithmExpression: t_order_item_$->{order_id % 2}
        shardingColumn: order_id



# 项目相关配置都在zk已经自动注册了

配置中心数据结构

配置中心在定义的命名空间的config下,以YAML格式存储,包括数据源,数据分片,读写分离、Properties配置,可通过修改节点来实现对于配置的动态管理。

config
    ├──authentication                            # Sharding-Proxy权限配置
    ├──props                                     # 属性配置
    ├──schema                                    # Schema配置
    ├      ├──sharding_db                        # SchemaName配置
    ├      ├      ├──datasource                  # 数据源配置
    ├      ├      ├──rule                        # 数据分片规则配置
    ├      ├──masterslave_db                     # SchemaName配置
    ├      ├      ├──datasource                  # 数据源配置
    ├      ├      ├──rule                        # 读写分离规则

相关配置说明:https://shardingsphere.apache.org/document/legacy/4.x/document/cn/features/orchestration/config-center/

5、验证:配置中心修改配置对项目立即生效,以打印sql属性为例

创建AddressMapper

@Mapper
public interface AddressMapper {

    /**
     * 新增地址
     *
     * @param address
     */
    @Insert("insert into t_address(address_id,address_name) values(#{addressId},#{addressName})")
    void insertAddress(Address address);

    /**
     * 删除所有地址(方便再次执行)
     */
    @Delete("delete from t_address")
    void deleteAllAddress();
}

创建单元测试

@Slf4j
@SpringBootTest
class ShardingSphereDemo7ApplicationTests {

    @Resource
    private AddressMapper addressMapper;

    @Test
    public void insertAddress() throws InterruptedException {
        Address address1 = new Address();
        address1.setAddressId(1L);
        address1.setAddressName("地址1");
        addressMapper.insertAddress(address1);
        Address address2 = new Address();
        address2.setAddressId(2L);
        address2.setAddressName("地址2");
        addressMapper.insertAddress(address2);
        log.info("这里开始睡眠20s——————————————>");
        // 睡眠20s用于修改配置
        Thread.sleep(20000);
        log.info("睡眠结束——————————————");
        Address address3 = new Address();
        address3.setAddressId(3L);
        address3.setAddressName("地址3");
        addressMapper.insertAddress(address3);
        Address address4 = new Address();
        address4.setAddressId(4L);
        address4.setAddressName("地址4");
        addressMapper.insertAddress(address4);

        addressMapper.deleteAllAddress();
    }

}

启动测试用例,并在睡眠时间内修改sql.show为false。

[zk: zk1:2181,zk2:2181,zk3:2181(CONNECTED) 32] set /orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/props 'sql.show: false'

日志打印

2021-07-23 13:52:18.213  INFO 71984 --- [           main] .z.s.ShardingSphereDemo7ApplicationTests : Started ShardingSphereDemo7ApplicationTests in 4.672 seconds (JVM running for 6.374)
# 项目启动完成,执行前两个insertAddress,打印了sql日志
2021-07-23 13:52:19.038  INFO 71984 --- [           main] ShardingSphere-SQL                       : Logic SQL: insert into t_address(address_id,address_name) values(?,?)
2021-07-23 13:52:19.038  INFO 71984 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@2bcda694, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@2cc75b25), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@2cc75b25, columnNames=[address_id, address_name], insertValueContexts=[InsertValueContext(parametersCount=2, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=54, stopIndex=54, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=56, stopIndex=56, parameterMarkerIndex=1)], parameters=[1, 地址1])], generatedKeyContext=Optional.empty)
2021-07-23 13:52:19.039  INFO 71984 --- [           main] ShardingSphere-SQL                       : Actual SQL: ds0 ::: insert into t_address(address_id,address_name) values(?, ?) ::: [1, 地址1]
2021-07-23 13:52:19.039  INFO 71984 --- [           main] ShardingSphere-SQL                       : Actual SQL: ds1 ::: insert into t_address(address_id,address_name) values(?, ?) ::: [1, 地址1]
2021-07-23 13:52:19.087  INFO 71984 --- [           main] ShardingSphere-SQL                       : Logic SQL: insert into t_address(address_id,address_name) values(?,?)
2021-07-23 13:52:19.088  INFO 71984 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@2bcda694, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@5be4be74), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@5be4be74, columnNames=[address_id, address_name], insertValueContexts=[InsertValueContext(parametersCount=2, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=54, stopIndex=54, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=56, stopIndex=56, parameterMarkerIndex=1)], parameters=[2, 地址2])], generatedKeyContext=Optional.empty)
2021-07-23 13:52:19.088  INFO 71984 --- [           main] ShardingSphere-SQL                       : Actual SQL: ds0 ::: insert into t_address(address_id,address_name) values(?, ?) ::: [2, 地址2]
2021-07-23 13:52:19.088  INFO 71984 --- [           main] ShardingSphere-SQL                       : Actual SQL: ds1 ::: insert into t_address(address_id,address_name) values(?, ?) ::: [2, 地址2]
# 线程开始sleep 20s
2021-07-23 13:52:19.103  INFO 71984 --- [           main] .z.s.ShardingSphereDemo7ApplicationTests : 这里开始睡眠20s——————————————>
# 此时执行了 set /orchestration-spring-boot-demo/demo_spring_boot_ds_sharding/config/props 'sql.show: false'
2021-07-23 13:52:21.482  INFO 71984 --- [tor-TreeCache-6] o.a.s.core.log.ConfigurationLogger       : ShardingRuleConfiguration:
bindingTables:
- t_order
- t_order_item
broadcastTables:
- t_address
defaultDataSourceName: ds0
defaultDatabaseStrategy:
  inline:
    algorithmExpression: ds$->{user_id % 2}
    shardingColumn: user_id
tables:
  t_order:
    actualDataNodes: ds$->{0..1}.t_order_$->{0..1}
    keyGenerator:
      column: order_id
      props:
        worker.id: '123'
      type: SNOWFLAKE
    logicTable: t_order
    tableStrategy:
      inline:
        algorithmExpression: t_order_$->{order_id % 2}
        shardingColumn: order_id
  t_order_item:
    actualDataNodes: ds$->{0..1}.t_order_item_$->{0..1}
    keyGenerator:
      column: order_item_id
      props:
        worker.id: '123'
      type: SNOWFLAKE
    logicTable: t_order_item
    tableStrategy:
      inline:
        algorithmExpression: t_order_item_$->{order_id % 2}
        shardingColumn: order_id

2021-07-23 13:52:21.482  INFO 71984 --- [tor-TreeCache-6] o.a.s.core.log.ConfigurationLogger       : Properties:
sql.show: false

2021-07-23 13:52:21.490  INFO 71984 --- [tor-TreeCache-6] ShardingSphere-metadata                  : Loading 2 logic tables' meta data.
2021-07-23 13:52:21.541  INFO 71984 --- [tor-TreeCache-6] ShardingSphere-metadata                  : Loading 5 tables' meta data.
2021-07-23 13:52:21.634  INFO 71984 --- [tor-TreeCache-6] ShardingSphere-metadata                  : Meta data load finished, cost 152 milliseconds.
# 重新加载了相关配置
2021-07-23 13:52:39.108  INFO 71984 --- [           main] .z.s.ShardingSphereDemo7ApplicationTests : 睡眠结束——————————————
# sleep结束后,没有打印sql日志
2021-07-23 13:52:39.187  INFO 71984 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

从上面的日志可以看出,在配置中心修改配置,立即对本地项目配置生效。

6、验证:直接使用配置中心配置

官方示例配置

# 需要的编排类型
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.orchestration-type=registry_center,config_center
# 配置中心类型。如:zookeeper
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.instance-type=zookeeper
# 连接注册中心服务器的列表。包括IP地址和端口号。多个地址用逗号分隔。如: host1:2181,host2:2181
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.server-lists=192.168.20.56:2181
# 注册中心的命名空间
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.namespace=orchestration-spring-boot-demo
# 本地配置是否覆盖注册中心配置。如果可覆盖,每次启动都以本地配置为准
spring.shardingsphere.orchestration.demo_spring_boot_ds_sharding.props.overwrite=false

当启动时会报错:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.reflect.InvocationTargetException

本地项目还是得加上相关的数据源和分片配置,否则会报错~

小结

总的来说配置中心和微服务中配置中心没什么区别,这里注册中心还没有相关研究,后面再进行补充。

源码

github

[码云](

0

评论区