我有一个java应用程序运行在tomcat上。我想把它连接到我的MySQL集群
在集群中我有三个SQL节点。我想尝试连接到所有三个节点,然后采用最快返回给我的连接!
我该怎么做呢?性能对我来说真的很重要。
到目前为止我写的是:
连接器类
public class Connecter extends Thread {
String dbURL;
String dbDriver = "com.mysql.jdbc.Driver";
Connection dbCon = null;
public Connecter(String dbURL) {
this.dbURL = dbURL;
}
@Override
public void run() {
try {
Class.forName(dbDriver);
try {
dbCon = DriverManager.getConnection(dbURL, "root", "");
} catch (SQLException ex) {
}
} catch (ClassNotFoundException ex) {
}
}
}
一个更接近的类
public void run() {
try {
dbCon.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (NullPointerException e) {}
}
和一个DbBean试图通过这个方法连接:
String dbURL1 = "jdbc:mysql://192.168.0.3/bank";
String dbURL2 = "jdbc:mysql://192.168.0.4/bank";
String dbURL3 = "jdbc:mysql://192.168.0.5/bank";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
public boolean connect() throws ClassNotFoundException, SQLException, InterruptedException {
Class.forName(dbDriver);
Connecter one = new Connecter(dbURL1);
Connecter two = new Connecter(dbURL2);
Connecter three = new Connecter(dbURL3);
Closer a = new Closer (one.dbCon);
Closer b = new Closer (two.dbCon);
Closer c = new Closer (three.dbCon);
one.start();
two.start();
three.start();
while(one.isAlive() && two.isAlive() && three.isAlive()){
Thread.sleep(10);
}
if(one.dbCon != null) {
this.dbCon = one.dbCon;
two.interrupt();
b.start();
three.interrupt();
c.start();
return true;
} else {
one.interrupt();
a.start();
}
if(two.dbCon != null) {
this.dbCon = two.dbCon;
one.interrupt();
a.start();
three.interrupt();
c.start();
return true;
} else {
two.interrupt();
b.start();
}
if(three.dbCon != null) {
this.dbCon = three.dbCon;
one.interrupt();
a.start();
two.interrupt();
b.start();
return true;
} else {
three.interrupt();
c.start();
}
return false;
}
只需使用支持连接池的数据库(任何现代RDBMS都支持此功能)并使用开箱即用的解决方案,例如DataSource
或c3p0。
参见官方JDBC教程。
我不确定的一件事是,你是想要连接池还是更高级的集群。但是,无论如何,我怀疑MySQL能否提供生产稳定的集群,据我所知,Oracle通过它的JDBC驱动程序透明地支持集群。