MySQL 讀寫分離實例詳解
MySQL 讀寫分離
MySQL讀寫分離又一好辦法 使用 com.mysql.jdbc.ReplicationDriver
在用過Amoeba 和 Cobar,還有dbware 等讀寫分離組件后,今天我的一個好朋友跟我講,MySQL自身的也是可以讀寫分離的,因為他們提供了一個新的驅動,叫 com.mysql.jdbc.ReplicationDriver
說明文檔:http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-replication-connection.html
代碼例子:
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import com.mysql.jdbc.ReplicationDriver;
public class ReplicationDriverDemo {
public static void main(String[] args) throws Exception {
ReplicationDriver driver = new ReplicationDriver();
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", "bar");
//
// 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 =
driver.connect("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");
.......
}
}
感謝閱讀,希望能幫助到大家,謝謝大對本站的支持!
相關文章
當面試官問mysql中char與varchar的區(qū)別
這篇文章主要以聊天形式圖片的添加,將面試官面試真實場景體現出來,好奇的朋友不要錯過奧2021-08-08
遠程連接mysql數據庫注意事項記錄(遠程連接慢skip-name-resolve)
有時候我們需要遠程連接mysql數據庫,就需要注意下面的問題,方便大家解決,腳本之家小編特為大家準備了一些資料2012-07-07
IntelliJ?IDEA?2024與MySQL?8連接以及driver問題解決辦法
在IDE開發(fā)工具中也是可以使用mysql的,下面這篇文章主要給大家介紹了關于IntelliJ?IDEA?2024與MySQL?8連接以及driver問題解決辦法,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-09-09
MySql插入數據成功但是報[Err] 1055錯誤的解決方案
這篇文章主要介紹了MySql插入數據成功但是報[Err] 1055錯誤的解決方案,需要的朋友可以參考下2017-08-08

