ZBLOG

sharding-proxy读写分离,主库不在线的情况下,无法启动sharding-proxy

在 ShardingSphere-Proxy 中,如果配置了读写分离(且主库是必须存在的默认数据源),当主库不可用时,ShardingSphere-Proxy 可能无法正常启动,这是因为:


🔍 原因分析

  1. 启动时数据源健康检查
    ShardingSphere-Proxy 在启动时会尝试初始化所有配置的数据源(包括主库和从库)。如果主库无法连接(例如网络问题、数据库宕机),初始化会失败,导致 Proxy 启动中止。

  2. 读写分离规则依赖主库
    即使你配置了多个从库,但读写分离规则通常要求一个可写的主库作为默认数据源。若主库不可用,整个逻辑数据库(schema)的初始化会失败。

  3. 缺乏部分降级能力
    早期版本的 ShardingSphere-Proxy 可能不支持“忽略不可用数据源”或“延迟初始化”机制,因此必须所有数据源均在线才能启动。


✅ 解决方案

方案1:临时绕过主库检查(适用紧急场景)

如果只是临时需要启动 Proxy(例如主库短暂故障但需先启用从库读取),可以尝试以下修改:

  1. 调整数据源配置
    config-sharding.yamlconfig-readwrite-splitting.yaml 中,暂时注释或移除主库配置,仅保留从库(但注意:此时代码中的写操作会失败)。

    dataSources:
     # primary_ds:  # 注释主库
     #   url: ...
     replica_ds_0:
       url: ...
     replica_ds_1:
       url: ...
    
  2. 使用虚拟数据源(hack方式)
    如果必须保留主库配置,可尝试提供一个虚假的主库连接(如一个无效的 URL),但此方法可能导致后续写操作异常,仅用于临时启动。


方案2:启用弹性数据源(推荐)

ShardingSphere 5.x+ 版本支持弹性数据源(即允许数据源启动时不可用,并在后续自动重连)。需满足:

  • 使用 ShardingSphere >= 5.1.0
  • 在数据源配置中开启 connectionInitSql 和故障转移参数。

示例配置(YAML):

dataSources:
  primary_ds:
    url: jdbc:mysql://primary_host:3306/db
    username: root
    password: root
    connectionTimeoutMilliseconds: 3000  # 连接超时时间
    initializationFailTimeout: -1        # 初始化失败时不立即中断(-1表示不中断)
    maxLifetimeMilliseconds: 1800000
    readOnly: false
  replica_ds_0:
    url: jdbc:mysql://replica_host:3306/db
    username: root
    password: root
    readOnly: true

rules:
- !READWRITE_SPLITTING
  dataSources:
    write_db:
      type: Static
      props:
        write-data-source-name: primary_ds
        read-data-source-names: replica_ds_0
      # 启用健康检查与自动切换
      loadBalancerName: round_robin

同时需在 server.yaml 中开启数据库发现与健康检查:

props:
  sql-show: true
  # 启用数据源健康检查
  check-database-metadata-enabled: true

📌重要说明:

  1. 版本兼容性:

    • Elastic data source feature requires at least version 5.1.0. For earlier versions, consider upgrading or using a temporary solution.
  2. If the master database is permanently unavailable, you should first restore the master database or adjust the architecture (e.g., promote a slave to master).

  3. Production environment recommendation:

    • Use a database high availability solution (e.g., MySQL MHA, PostgreSQL streaming replication).
    • Combine with connection pool retry mechanisms (such as HikariCP’s connection-timeout and initialization-fail-timeout).

If you are using an older version and cannot upgrade temporarily, you may need to manually modify the source code or wait for the master database to recover before starting.

Would you like guidance on any of these specific solutions?


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=24228

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?