Java JPA 负载平衡读取查询以读取 MySql DB 从站

标签 java mysql hibernate jpa playframework

我注意到我的 Play Framework 应用程序没有将读取查询发送到只读的 MySql 从服务器。

我正在使用

  1. com.mysql.cj.jdbc.Driver 作为javax.persistence.jdbc.driver
  2. jdbc:mysql:replication://write-db-url,read-db-url/db_name 作为 javax.persistence.jdbc.url
  3. 数据库是 AWS aurora MySQL 兼容,具有 multi-az 副本。
  4. 我正在使用 hibernate 作为 ORM。
  5. 我正在使用 play framework

我是否缺少任何配置/代码?

最佳答案

其他一切看起来都不错,如问题所述,例如 jdbc driverurl

因为在您的问题中提供的与 ORM 或 JPA 以及您正在使用的连接代码相关的信息非常少。

我在这里提供了一个简单的主程序,您可以使用它来调试您的问题。完成后,专注于您的应用,看看您是否错过了同样的事情。

这里是JDBC 驱动程序如何确定是连接master 还是read replica

  1. 如果连接模式是read+write,这是default,那么它会转到master
  2. 如果连接模式是read,那么它将转到read-replica之一。

这里正式documentation .

import java.sql.Connection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import java.sql.DriverManager;

public class ReplicationDemo {

public static void main(String[] args) throws Exception {

Properties props = new Properties();

// We want this for failover on the slaves
props.put("autoReconnect", "true");

// We want to load balance between the slaves
props.put("roundRobinLoadBalance", "true");

props.put("user", "foo");
props.put("password", "password");

//
// Looks like a normal MySQL JDBC url, with a
// comma-separated list of hosts, the first
// being the 'master', the rest being any number
// of slaves that the driver will load balance against
//

Connection conn =
    DriverManager.getConnection("jdbc:mysql:replication://master,slave1,slave2,slave3/test",
        props);

//
// Perform read/write work on the master
// by setting the read-only flag to "false"
//

conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATE some_table ....");
conn.commit();

//
// Now, do a query from a slave, the driver automatically picks one
// from the list
//

conn.setReadOnly(true);

ResultSet rs =
  conn.createStatement().executeQuery("SELECT a,b FROM alt_table");

 .......
}
}

希望对您有所帮助。

关于Java JPA 负载平衡读取查询以读取 MySql DB 从站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933802/

相关文章:

java - Maven:从存储库下载父 pom 会删除存储库标签

mysql-server 每天 7 点删除

php - 搜索多列 mysql 和 php

java - 如何使用@EmbeddedId映射实体?

hibernate - JPA/Hibernate 批量插入缓慢

oracle - Hibernate @OrderBy 与引用的类

java - 在 JavaFX Spinner 中手动输入文本不会更新值(除非用户按 ENTER)

java - Struts2 Java Util日期转换问题

java - ActionListener 不起作用

php - 语法 mysql/php 错误