ShardingProxy

前面我们学习了Sharding-JDBC,对于ShardingSphere的分库分表规则配置已经有了一定的认识。实际上,Sharding-Proxy在配置上与Sharding-JDBC基本一致,只不过Sharding-JDBC嵌入在应用程序中,而Sharding-Proxy是一个独立的中间件。这里我们继续学习Sharding-Proxy的使用。

下载运行Sharding-Proxy

Sharding-Proxy的下载链接可以在ShardingSphere官网找到。我们下载apache-shardingsphere-5.1.1-shardingsphere-proxy-bin.tar.gz文件,将其解压即可。

https://archive.apache.org/dist/shardingsphere/5.1.1/

此外,我们还需要将MySQL驱动文件放在ext-lib文件夹中(没有该文件夹可以手动创建),我这里使用的是mysql-connector-java-8.0.30.jar

我们还需要修改配置文件conf/server.yaml,其中有一些例子配置,我们根据提示配置即可。我们这里简单起见,仅配置下用户权限和显示SQL数据,分布式调度模式未配置时默认使用Memory模式,这里节省篇幅就使用默认方式了,但注意生产环境中我们需要将其配置到ZooKeeper。

rules:
  - !AUTHORITY
    users:
      - root@%:root
    provider:
      type: ALL_PRIVILEGES_PERMITTED
props:
  sql-show: true

配置完成后我们可以尝试启动Sharding-Proxy,找到bin目录的start.bat(Linux下为start.sh),执行以下命令:

start.bat 30000

Sharding-Proxy服务会在30000端口启动,如果端口号不指定,默认会在3307端口启动。

配置Sharding-Proxy

Sharding-Proxy的配置都在conf目录中,我们可以打开相关的配置文件,读写分离规则可以在config-readwrite-splitting.yaml中进行配置,分库分表规则可以在config-sharding.yaml中进行配置,其中的配置内容其实和之前的Sharding-JDBC中的配置是类似的。下面我们尝试配置一个读写分离的数据源。修改config-readwrite-splitting.yaml文件,写入以下内容。

schemaName: netstore

dataSources:
  write_ds:
    url: jdbc:mysql://127.0.0.1:3306/netstore
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
    minPoolSize: 1
  read_ds:
    url: jdbc:mysql://127.0.0.1:3307/netstore
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
    minPoolSize: 1

rules:
- !READWRITE_SPLITTING
  dataSources:
    readwrite_ds:
      type: Static
      props:
        write-data-source-name: write_ds
        read-data-source-names: read_ds

此时重启Sharding-Proxy,我们可以使用任何客户端连接Sharding-Proxy服务,查看配置效果。

这里使用Navicat客户端连接了Sharding-Proxy,可以看到相关的数据。我们可以使用客户端进行插入和查询操作,并查看Sharding-Proxy中输出的SQL语句。

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。
Copyright © 2017-2024 Gacfox All Rights Reserved.
Build with NextJS | Sitemap