使用 Spring Cloud AWS RDS Aurora 的 Spring Boot 应用程序 - 如何分发读取查询

str*_*y05 12 java spring-boot amazon-aurora spring-cloud-aws

我有一个使用 AWS RDS 数据库的 Spring Boot 应用程序。

我正在尝试让 RDS Aurora / Postgres DB 与只读副本一起使用。我已经运行了应用程序,但是我看不到任何流向读取器节点的流量。

设置的是 Spring boot (2.2.7)、spring cloud aws 2.2.4-RELEASE、spring data (JpaRepository)。

RDS Aurora 集群有 2 个节点、1 个读取器和 1 个写入器,如下所示: AWS RDS 配置

控制器 GET 方法注释为@Transactional(readOnly = true)

    @RequestMapping(
            value = "/counters",
            produces = {"application/json"},
            method = RequestMethod.GET
    )
    @ResponseBody
    @Transactional(readOnly = true)
    public ResponseEntity<List<Counter>> getCounters()  {
        return ResponseEntity.of(Optional.of(this.counterDAO.findAll()));
    }
Run Code Online (Sandbox Code Playgroud)

最后Spring Cloud AWS配置

cloud:
  aws:
    region:
      static: ap-southeast-2
    credentials:
      accessKey: ${ACCESS_KEY}
      secretKey: ${SECRET_KEY}
    rds:
      rds-db-cluster-instance-1:
        password: ${POSTGRES_PASSWORD}
        username: postgres
        readReplicaSupport: "true"
        databaseName: postgres
    stack:
      auto: false
Run Code Online (Sandbox Code Playgroud)

此时,我可以从数据库读取和写入,但是我没有看到任何证据表明它正在使用读取器节点。

该应用程序仅在我使用编写器实例名称作为 时启动cloud.aws.rds.<instance-id>,使用集群名称时它不起作用(使用编写器 id 可能是配置它的正确方法,文档不太清楚)并且如果我使用只读实例 id,更新数据库的方法失败。

AWS 控制台上的监控仅显示 Writer 节点上的连接(我可以通过 2 个调用 GET 和 POST 方法的线程将其增加到 10 - 15 个连接),但是 Reader 节点始终为 0。

其次,我在ReadOnlyRoutingDataSource类上使用调试器设置了断点,这些断点从未被命中,所以我很确定它没有使用只读功能。

我相当确定这是由于我正在使用的实例 ID 造成的,也许与底层 RDS 配置有关,但我一生都无法解决这个问题。

stm*_*tmi 1

您需要显式配置 2 个数据源。在 AWS 中,只读副本将具有单独的 url,并-ro添加为屏幕截图中可见的内容。

有关如何配置 2 个数据源的信息,请参阅 Spring Boot 文档部分8.2. Configure Two DataSources

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.data-access.configure-two-datasources

EntityManager配置完 2 个数据源后,您需要为每个 RO 和 RW 存储库 创建单独的存储库,如第 1 节中所述8.10. Using Multiple EntityManagerFactories

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.data-access.use-multiple-entity-managers

然后在服务中,您需要提供包含 RO 和/或 RW 存储库的字段以进行查询。