首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java负载平衡读取查询以读取MySql DB从服务器

Java负载平衡读取查询以读取MySql DB从服务器
EN

Stack Overflow用户
提问于 2019-07-08 11:19:37
回答 1查看 633关注 0票数 3

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

我在用

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

我缺少任何配置/代码吗?

EN

回答 1

Stack Overflow用户

发布于 2019-07-12 09:29:56

其他一切看起来都很不错,比如jdbc driverurl

因为在您的问题中,提供的有关ORM或JPA和您正在使用的连接代码的信息非常少。

我在这里提供了一个简单的主程序,您可以使用调试问题。一旦完成,关注你的应用程序,看看,你是不是错过了同样的事情。

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

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

这里是正式的文档

代码语言:javascript
复制
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");

 .......
}
}

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56933802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档