博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql 读写分离驱动插件
阅读量:4106 次
发布时间:2019-05-25

本文共 1417 字,大约阅读时间需要 4 分钟。

在用过Amoeba 和 Cobar,还有dbware 等读写分离组件后,今天我的一个好朋友跟我讲,MySQL自身的也是可以读写分离的,因为他们提供了一个新的驱动,叫 com.mysql.jdbc.ReplicationDriver

 

说明文档:

 

代码例子:

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"
);
 
     
.......
  
}
}

转载地址:http://itnsi.baihongyu.com/

你可能感兴趣的文章
Java编程基础:static的用法
查看>>
Java编程基础:抽象类和接口
查看>>
Java编程基础:异常处理
查看>>
Spring MVC中使用Thymeleaf模板引擎
查看>>
Spring处理表单提交
查看>>
Spring MVC异常处理
查看>>
Leetcode 1180. Count Substrings with Only One Distinct Letter [Python]
查看>>
PHP 7 的五大新特性
查看>>
php实现socket(转)
查看>>
PHP底层的运行机制与原理
查看>>
深入了解php底层机制
查看>>
PHP中的stdClass 【转】
查看>>
XHProf-php轻量级的性能分析工具
查看>>
PHP7新特性 What will be in PHP 7/PHPNG
查看>>
比较strtr, str_replace和preg_replace三个函数的效率
查看>>
ubuntu 下编译PHP5.5.7问题:configure: error: freetype.h not found.
查看>>
PHP编译configure时常见错误 debian centos
查看>>
configure: error: Please reinstall the BZip2 distribution
查看>>
OpenCV gpu模块样例注释:video_reader.cpp
查看>>
【增强学习在无人驾驶中的应用】
查看>>