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
    评论
要使用JDBC连接MySQL集群,可以按照以下步骤进行操作: 1. 首先,确保你已经在Java开发环境中导入了MySQLJDBC驱动程序。你可以从MySQL官方网站上下载并安装它,或者使用一些构建工具(如Maven或Gradle)来引入依赖。 2. 在你的Java代码中,使用以下语句加载MySQLJDBC驱动程序: ```java Class.forName("com.mysql.cj.jdbc.Driver"); ``` 请注意,根据你的MySQL版本和驱动程序版本,驱动程序类名可能会有所不同。 3. 创建一个JDBC连接字符串,指定MySQL集群连接信息。该连接字符串的格式通常如下: ``` jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]?property1=value1&property2=value2... ``` 其中,`[host1]`、`[host2]`等是MySQL集群中的各个主机名(或IP地址),`[:port1]`、`[:port2]`等是各个主机的端口号(如果不指定,默认为3306),`/[database]`是要连接的数据库名,`?property1=value1&property2=value2...`是可选的连接属性。 4. 使用上述连接字符串、用户名和密码创建一个数据库连接对象。例如: ```java String url = "jdbc:mysql://host1:port1,host2:port2/database"; String user = "your_username"; String password = "your_password"; Connection conn = DriverManager.getConnection(url, user, password); ``` 请将`host1`、`port1`等替换为实际的主机名、端口号和数据库名,以及`your_username`和`your_password`替换为你的数据库用户名和密码。 5. 现在你可以使用该连接对象执行SQL查询和更新操作了。例如: ```java Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM your_table"); while (rs.next()) { // 处理结果集 } rs.close(); stmt.close(); ``` 记得在使用完毕后关闭连接和相关资源。 这样,你就可以使用JDBC连接MySQL集群了。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值