您的位置:首页 > 数据库 > MySQL

JDBC进行Mysql读写分离测试

2016-04-07 17:06 465 查看
在程序中添加两个数据源、分别对应读跟写:

#读#
DBDriver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:loadbalance\://10.11.0.75,172.16.0.202\:3306/DB_TEST7?roundRobinLoadBalance\=true&characterEncoding\=UTF-8
name=TESTUSER
pass=TESTPWD
characterEncoding=utf8


#写#
DBDriver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:loadbalance\://10.11.2.126\:3306/DB_TEST7?roundRobinLoadBalance\=true&characterEncoding\=UTF-8
name=TESTUSER
pass=TESTPWD
characterEncoding=utf8
测试类:

/**
* 数据连接类
* @author 胡汉三
*
*/
public class UtilDao {
static Properties properties = null;
public UtilDao(String rw){
//读取属性文件
properties = new Properties();
java.io.InputStream in = null;
if(rw.equals("R")){
in = (java.io.InputStream) this.getClass()
.getResourceAsStream("/mysqlDBR.properties");
}else if (rw.equals("W")){
in = (java.io.InputStream) this.getClass()
.getResourceAsStream("/mysqlDBW.properties");
}
try {
properties.load(in);
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public Connection getConn(){
Connection connection = null;
try{
Class.forName(properties.getProperty("DBDriver"));
connection = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("name"),properties.getProperty("pass"));
}catch (Exception err) {
System.out.println("连接ConDB-->getCon()____JDBC错误!");
err.printStackTrace();
return null;
}
return connection;
}

public static void main(String[] args) throws SQLException {
UtilDao uW = new UtilDao("W");
UtilDao uR = new UtilDao("R");
Connection connR = uR.getConn();  //connectionsToHostsMap()
Connection connW = uW.getConn();  //connectionsToHostsMap()
connW.setAutoCommit(false);  //自动提交为False
connR.setAutoCommit(false);  //自动提交为False
String inSql = "insert into city(sname) values('复制')";
String sql = "select * from city where sname = '复制'";
Statement sW = connW.createStatement();
Statement sR = connR.createStatement();
try {
sW.execute(inSql);
connW.commit();
} catch (Exception e) {
connW.rollback();
e.printStackTrace();
}
ResultSet r = sR.executeQuery(sql);
int l = 0 ;
while (r.next()){
System.out.println(r.getString("sname")+" " +r.getString("Id")+"    第:"+l+"条");
l++;
}
r.close();
sW.close();
sR.close();
connW.close();
connR.close();
}


输出:

复制 737    第:0条
复制 738    第:1条
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: