mysql 集群 jdbc配置

项目中使用mysql 主从复制,但是用程序实现的读写分离,代码片段如下:

1 public DataSource getDataSource(MethodType methodType) {
2 if (methodType == MethodType.WRITE) {
3 return getDataSource(MasterDataSources);
4 } else {
5 return getDataSource(SlaveDataSources);
6 }
7 }


获取数据源,首先你要确定MethodType 类型,一个是读,一个是写

1 public enum MethodType {
2 READ, WRITE
3 }

读是获取从库数据源,写是获取主库数据源。

这样,就需要在jdbc配置配置两个数据源(一主一从)

还有另一种实现方式,不用程序来控制。mysql 驱动包提供相应的实现 com.mysql.jdbc.ReplicationDriver.
我写了一个简单的例子:

1 package com.howard.loadbalance;
2
3 import java.sql.Connection;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.sql.Statement;
7 import java.util.Properties;
8 import java.util.concurrent.ExecutorService;
9 import java.util.concurrent.Executors;
10
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 import com.mysql.jdbc.ReplicationDriver;
15
16 public class MysqlTest {
17
18 public static class QueryRunnable implements Runnable {
19
20 protected final static Logger logger = LoggerFactory
21 .getLogger(QueryRunnable. class );
22
23 @Override
24 public void run() {
25 logger.info( " user size: " + this .query());
26 }
27
28 public int query() {
29 int count = 0 ;
30 try {
31 ReplicationDriver driver = new ReplicationDriver();
32 Properties props = new Properties();
33 props.put( " roundRobinLoadBalance " , " true " );
34 props.put( " autoReconnect " , " true " );
35 props.put( " user " , " core " );
36 props.put( " password " , " core " );
37 Connection conn = null ;
38 Statement stat = null ;
39 ResultSet res = null ;
40 try {
41 conn = driver
42 .connect(
43 // 注意url串中间不要有空格,因为mysql源码对多个地址split时没有trim.
44 " jdbc:mysql:replication://127.0.0.1:3309,127.0.0.1:3306/core " ,
45 props);
46 // 读写分离标记
47 // 当设置true时,只会在从库查询数据
48 // 当设置false时,会在主库做更新删除操作
49 // conn.setReadOnly(true);
50 stat = conn.createStatement();
51 res = stat.executeQuery( " select count(1) from c_user " );
52 while (res.next())
53 count = res.getInt( 1 );
54 } finally {
55 if (res != null )
56 res.close();
57 if (stat != null )
58 stat.close();
59 if (conn != null )
60 conn.close();
61 }
62 } catch (SQLException e) {
63 e.printStackTrace();
64 }
65 return count;
66 }
67 }
68
69 public static void main(String[] args) {
70 // 创建线程池测试负载军衡
71 ExecutorService service = Executors.newCachedThreadPool();
72 for ( int i = 0 ; i < 10 ; i ++ ) {
73 service.execute( new QueryRunnable());
74 }
75 service.shutdown();
76 }
77
78 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值