sharding-jdbc讀寫分離
阿新 • • 發佈:2018-12-18
分庫分表 遲早會用到,有空學學瞭解先。
參考:http://shardingsphere.io/document/current/cn/overview/
當前demo,普通Java格式,沒有spring或springboot整合。。。後期加入。。。
-----------------------------------------------------------------------------------------------------------------
pom.xml
<dependency> <groupId>io.shardingsphere</groupId
> <artifactId>sharding-jdbc-core</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency>Java:
package cn.ywj;import io.shardingsphere.api.config.MasterSlaveRuleConfiguration;import io.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;import
org.apache.commons.dbcp.BasicDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Properties;public class Ttest { // 直接拋異常,省點事,人懶 public static void main(String[] args) throws SQLException { // 兩個資料來源 Map<String, DataSource> result = new HashMap<>(); // 主庫 BasicDataSource ds_master = new BasicDataSource(); ds_master.setDriverClassName(com.mysql.jdbc.Driver.class.getName()); ds_master.setUrl("jdbc:mysql://localhost:3306/ds_master?useSSL=false"); ds_master.setUsername("root"); ds_master.setPassword("123"); result.put("ds_master", ds_master); // 從庫 BasicDataSource ds_slave0 = new BasicDataSource(); ds_slave0.setDriverClassName(com.mysql.jdbc.Driver.class.getName()); ds_slave0.setUrl("jdbc:mysql://localhost:3308/ds_slave?useSSL=false"); ds_slave0.setUsername("root"); ds_slave0.setPassword("123"); result.put("ds_slave", ds_slave0); // 主從配置宣告 MasterSlaveRuleConfiguration masterSlaveRuleConfiguration = new MasterSlaveRuleConfiguration("test_master_slave", "ds_master", Arrays.asList("ds_slave")); // 獲取資料來源 DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(result, masterSlaveRuleConfiguration, new HashMap<String, Object>(), new Properties()); // 執行讀操作 Connection connection = connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM USER"); ResultSet resultSet = preparedStatement.executeQuery(); // 此時的資料是從庫的 while (resultSet.next()) { System.out.println(resultSet.getLong(1) +" > "+resultSet.getString(2)); } resultSet.close(); preparedStatement.close(); // 執行寫操作-主庫 preparedStatement = connection.prepareStatement("INSERT INTO USER VALUES (?, ?)"); preparedStatement.setLong(1, 2L); preparedStatement.setString(2, "3306-msg"); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } }OK.
T:做好Mysql主從複製。
N:整合SpringBoot