分享一個MySQL ReplicationDriver類代碼

在 MySQL 復制的環境中,要通過 JDBC 連接這個 MySQL 集群,就必須使用 ReplicationDriver 這個類來替換原有的 com.mysql.jdbc.Driver 。不過該 Driver 在連接池環境下無效,要通過連接池連接 MySQL 集群可使用?lbpool。

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://master,slave1,slave2,slave3/test",  ????????????props);  ????//  ????//?Perform?read/write?work?on?the?master  ????//?by?setting?the?read-only?flag?to?"false"  ????//  ??//這個節點應該是通過spring的事務管理來設置,同時這個conn對象應該不是一個真正的connection,  	????//而是一個代理類,通過設置readonly,代理類會去使用不同的connection,  	????//那么問題是它該代理類使用的connection是哪里取的,抑或說難道它每次都會新開一個connection?,需要看源代碼  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");  ?????.......  ??}

? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享