## 模块 5：扩容/缩容或升降配 TiDB Dedicated 集群

+ 在本模块中，我们将向您展示如何轻松地扩容/缩容或升降配 TiDB Dedicated 集群。
+ 我们还演示了当启用 TiProxy 时，即使您的应用程序没有重连逻辑，在缩容期间您的应用程序也不会遇到连接中断。

### 步骤 1. 查看 `Modify` 面板

+ 点击右上角的 `...`，然后点击 `Modify`。

  ![80%](https://lab-static.pingcap.com/images/2025/7/24/42a6e12c6e4d5bbb12d85281d2cc6633b1a108b7.png)

+ 查看扩容/缩容或升降配 TiDB Dedicated 集群的选项。现在不要缩容您的集群。

### 步骤 2. 准备示例数据

+ 前往 [Terminal 1](ssh://monitor1-ssh#1)，导入一些示例数据。

  ```sql
  USE test
  CREATE TABLE `users` (
    `id` int,
    `name` varchar(100),
    `balance` int
  );
  INSERT INTO users VALUES (1, 'Alice', 10);
  INSERT INTO users VALUES (2, 'Bob', 20);
  ```

  ```sql
  exit
  ```

### 步骤 3. 阅读代码

+ 在 `demo_tiproxy_no_reconn.py` 中，初始化了 5 个连接。理论上，TiProxy 应该将它们平衡分配到 3 个 TiDB 服务器节点上。
+ 代码本身没有处理连接断开的逻辑，这在没有 TiProxy 的情况下缩容时可能会发生。
+ 由于这里使用了 TiProxy，运行程序时您不会看到任何错误消息打印出来。

### 步骤 4. 更新连接信息

+ 在 `demo_tiproxy_no_reconn.py` 中，更新连接信息

  ```output
  conn = connect(
    database="test",
    host="<host_address>",
    port=4000,
    user="root",
    password="<your password>",
    ssl_ca="/home/ubuntu/ca.pem",
    ssl_verify_cert=True,
    ssl_verify_identity=True,
  )
  ```

### 步骤 5. 安装必要的 Python 包

  ```bash
  sudo apt-get update
  sudo apt install python3.12-venv -y
  python3 -m venv myenv
  source myenv/bin/activate
  pip install --upgrade mysql-connector-python
  ```

  ```output
  ...
  Downloading mysql_connector_python-9.4.0-cp312-cp312-manylinux_2_28_x86_64.whl (33.9 MB)
    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 33.9/33.9 MB 69.8 MB/s eta 0:00:00
  Installing collected packages: mysql-connector-python
  Successfully installed mysql-connector-python-9.4.0
  ```

### 步骤 6. 运行 `demo_tiproxy_no_reconn.py`

  ```bash
  python3 demo_tiproxy_no_reconn.py
  ```

  ```output
  ...
  Thread 1: Committed. Alice balance updated to: 4
  Thread 4: Committed. Alice balance updated to: 5
  Thread 2: Committed. Alice balance updated to: 9
  Thread 5: Committed. Alice balance updated to: 6
  Thread 3: Committed. Alice balance updated to: 9
  Thread 1: Committed. Alice balance updated to: 10
  Thread 4: Committed. Alice balance updated to: 1
  Thread 2: Committed. Alice balance updated to: 3
  ...
  ```

### 步骤 7. 缩容一个 TiDB 服务器

+ 前往 TiDB Cloud Web UI，缩容 TiDB 服务器

  ![80%](https://lab-static.pingcap.com/images/2025/7/24/f655b919085c9ed2e3d754c04136cc512cb6d257.png)

+ 缩容可能需要超过 5 分钟才能完成。
+ 缩容时，请观察终端输出。您不应该看到任何错误消息打印出来。
+ 更多详情请参考此实验：[数据库扩容和缩容](/labs/demo_009)。

### 步骤 8. 停止工作负载

+ 在 [Terminal 1](ssh://monitor1-ssh#1) 中，使用 `ctrl` + `c`。

### 步骤 9. 删除 `TiDB Cloud Dedicated` 集群

+ 前往 `Overview`，点击 `...`，然后删除您的集群。

  ![80%](https://lab-static.pingcap.com/images/2025/7/24/a319028d778d0e722f741644e79f7e9d655ad37b.png)
