我注意到我的 Play Framework 应用程序没有将读取查询发送到只读的 MySql 从服务器。
我正在使用
com.mysql.cj.jdbc.Driver
作为javax.persistence.jdbc.driver
。jdbc:mysql:replication://write-db-url,read-db-url/db_name
作为javax.persistence.jdbc.url
- 数据库是
AWS aurora
MySQL 兼容
,具有multi-az
副本。 - 我正在使用
hibernate
作为 ORM。 - 我正在使用
play framework
。
我是否缺少任何配置/代码?
最佳答案
其他一切看起来都不错,如问题所述,例如 jdbc
driver
和 url
。
因为在您的问题中提供的与 ORM 或 JPA 以及您正在使用的连接代码相关的信息非常少。
我在这里提供了一个简单的主程序,您可以使用它来调试您的问题。完成后,专注于您的应用,看看您是否错过了同样的事情。
这里是JDBC
驱动程序如何确定是连接master
还是read replica
。
- 如果连接模式是
read+write
,这是default
,那么它会转到master
。 - 如果连接模式是
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/