MySQL Connector/J กับ round-robin


บังเอิญไปเจอ MySQL Bugs: #8643: Round-Robin doesn't work in some case. (ปัจจุบัน bug นี้ถุกแก้ไข...ไปนานแล้ว) เลยทำให้รู้ว่า MySQL Connector/J มี round-robin function ด้วย

MySQL Round-Robin ก็คือ ถ้ามี MySQL Server สอง 2 ตัว (เรียกว่า 2 node)

หาก node1 down ก็จะไปเรียกใช้ node2 แทน

import java.sql.*;
import java.util.*;

public class Bug8643
{
    public static void main(String[] args) throws Exception
    {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306,localhost:3307/test";
Properties props = new Properties();
props.put("autoReconnect", "true");
props.put("roundRobinLoadBalance", "true");
props.put("failOverReadOnly", "false");
props.put("user", "root");
props.put("password", "");

Connection con = DriverManager.getConnection(url, props);
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("show variables like 'port'");
rs.next();
System.out.println("connected to port:" + rs.getString(2));

rs = stmt.executeQuery("select connection_id()");
rs.next();
String originalConnectionId = rs.getString(1);
stmt.executeUpdate("kill " + originalConnectionId);
try {
     rs = stmt.executeQuery("show variables like 'port'");
} catch (SQLException ex) {
     // failover and retry
     rs = stmt.executeQuery("show variables like 'port'");
}
rs.next();
System.out.println("connected to port:" + rs.getString(2));
rs = stmt.executeQuery("select connection_id()");
rs.next();
originalConnectionId = rs.getString(1);
stmt.executeUpdate("kill " + originalConnectionId);
try {
     rs = stmt.executeQuery("show variables like 'port'");
} catch (SQLException ex) {
     // failover and retry
     rs = stmt.executeQuery("show variables like 'port'");
}
rs.next();
System.out.println("connected to port:" + rs.getString(2));
con.close();    
    }
}

ก็ดีนะ ง่ายดี แต่ PHP ไม่เห็นมีเลย สงสัยต้องเขียนเอาเอง sleep.gif

พูดถึง BUG หน่อย มันผิดตรงที่ Connection.java บรรทัด 2550
จาก
CODE
if (index[0] > hostList.size()) {
   index[0] = 0;
}

แก้เป็น
CODE
if (index[0] >= hostList.size()) {
   index[0] = 0;
}


... bug บางอย่าง ก็ไม่น่าเชื่อว่าจะหลุดได้ เค้าทดสอบกันยังไงเนี่ย
คำสำคัญ (Tags): #java#database
หมายเลขบันทึก: 18910เขียนเมื่อ 14 มีนาคม 2006 16:22 น. ()แก้ไขเมื่อ 22 พฤษภาคม 2012 09:39 น. ()สัญญาอนุญาต: จำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

ไม่มีความเห็น

พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท