database creation create database demo_ds_master; // Create the master database create database demo_ds_slave_0; // Create slave 1 create database demo_ds_slave_1; // Create slave 2 import dependencies <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.0</version> <scope>test</scope> </dependency>
<dependency> <groupId>io.shardingjdbc</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>2.0.0.M2</version> </dependency>
<dependency> <groupId>io.shardingjdbc</groupId> <artifactId>sharding-jdbc-spring-namespace</artifactId> <version>2.0.0.M2</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.13</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.28</version> </dependency>
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency>
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency> </dependencies>
代码: 1.创建数据源的工具类: import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; public class DataSourceUtil { private static final String URL_PREFIX = "jdbc:mysql://localhost:3306/"; private static final String USER_NAME = "root"; private static final String PASSWORD = "123456"; public static DataSource createDataSource(final String dataSourceName) { DruidDataSource result = new DruidDataSource(); result.setDriverClassName(com.mysql.jdbc.Driver.class.getName()); result.setUrl(URL_PREFIX + dataSourceName); result.setUsername(USER_NAME); result.setPassword(PASSWORD); return result; } } 2.主从数据库配置 package com.irisian.sharedjdbc.masterandslave; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory; import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration; public final class RawJdbcJavaMasterSlaveOnlyMain {
public static void main(String[] args) throws SQLException { new RawJdbcRepository(getMasterSlaveDataSource()).demo(); }
public static DataSource getMasterSlaveDataSource() throws SQLException { MasterSlaveRuleConfiguration masterSlaveRule = new MasterSlaveRuleConfiguration(); masterSlaveRule.setName("demo_ds_master_slave");//主从规则的名称,此名称随意起 masterSlaveRule.setMasterDataSourceName("demo_ds_master");//主数据源名称,和createDataSourceMap对象 masterSlaveRule.setSlaveDataSourceNames(Arrays.asList("demo_ds_slave_0", "demo_ds_slave_1"));//从数据源名称,和createDataSourceMap对象 masterSlaveRule.setLoadBalanceAlgorithmClassName( "io.shardingjdbc.core.api.algorithm.masterslave.RandomMasterSlaveLoadBalanceAlgorithm");//负载平衡的策略 return MasterSlaveDataSourceFactory.createDataSource(createDataSourceMap(), masterSlaveRule); }
private static Map<String, DataSource> createDataSourceMap() { final Map<String, DataSource> result = new HashMap<>(3, 1); result.put("demo_ds_master", DataSourceUtil.createDataSource("demo_ds_master"));//创建主库的数据源连接 result.put("demo_ds_slave_0", DataSourceUtil.createDataSource("demo_ds_slave_0"));//创建从库的数据源连接 result.put("demo_ds_slave_1", DataSourceUtil.createDataSource("demo_ds_slave_1"));//创建从库的数据源连接 return result; } }
3.测试的类 package com.irisian.sharedjdbc.masterandslave; import io.shardingjdbc.core.api.HintManager; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
public class RawJdbcRepository {
private final DataSource dataSource;
public RawJdbcRepository(final DataSource dataSource) { this.dataSource = dataSource; }
public void demo() throws SQLException { // createTable(); //创建表的语句
// insertData();//插入仅仅会插入到主数据源里面,然后配置mysql主从同步(需要自己配置,shareding-jdbc无法自动完成),配置了之后就可以从从库中读取了
//for (int i = 0; i < 30; i++) {//查询均从从库中读取,如果从库集中有一个数据库中没有数据,刚好从此数据库中读取数据,则读取不到任何的数据 //System.out.println("1.Equals Select--------------"); //printEqualsSelect(); //} System.out.println("1.Equals Select--------------"); printEqualsSelect();
// System.out.println("2.In Select--------------"); // printInSelect(); // System.out.println("3.Hint Select--------------"); // printHintSimpleSelect(); // dropTable();
}
public void createTable() throws SQLException { execute(dataSource, "CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT NOT NULL AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id))"); execute(dataSource, "CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT NOT NULL AUTO_INCREMENT, order_id BIGINT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (order_item_id))"); }
public void dropTable() throws SQLException { execute(dataSource, "DROP TABLE t_order_item"); execute(dataSource, "DROP TABLE t_order"); }
public void insertData() throws SQLException { for (int i = 1; i < 10; i++) { long orderId = executeAndGetGeneratedKey(dataSource, "INSERT INTO t_order (user_id, status) VALUES (10, 'INIT')"); execute(dataSource, String.format("INSERT INTO t_order_item (order_id, user_id) VALUES (%d, 10)", orderId)); orderId = executeAndGetGeneratedKey(dataSource, "INSERT INTO t_order (user_id, status) VALUES (11, 'INIT')"); execute(dataSource, String.format("INSERT INTO t_order_item (order_id, user_id) VALUES (%d, 11)", orderId)); } }
public void printEqualsSelect() throws SQLException { String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=?"; try (Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setInt(1, 10); printSimpleSelect(preparedStatement); } }
public void printInSelect() throws SQLException { String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id IN (?, ?)"; try (Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setInt(1, 10); preparedStatement.setInt(2, 11); printSimpleSelect(preparedStatement); } }
public void printHintSimpleSelect() throws SQLException { String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id"; try (HintManager hintManager = HintManager.getInstance(); Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { hintManager.addDatabaseShardingValue("t_order", "user_id", 11); printSimpleSelect(preparedStatement); } }
private void printSimpleSelect(final PreparedStatement preparedStatement) throws SQLException { StringBuilder builder = new StringBuilder(); try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { System.out.print("order_item_id:" + rs.getLong(1) + ", "); System.out.print("order_id:" + rs.getLong(2) + ", "); System.out.print("user_id:" + rs.getInt(3)); System.out.println(); } } }
private void execute(final DataSource dataSource, final String sql) throws SQLException { try (Connection conn = dataSource.getConnection(); Statement statement = conn.createStatement()) { statement.execute(sql); } }
private long executeAndGetGeneratedKey(final DataSource dataSource, final String sql) throws SQLException { long result = -1; try (Connection conn = dataSource.getConnection(); Statement statement = conn.createStatement()) { statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { result = resultSet.getLong(1); } } return result; } } |
The simplest and easy-to-understand example of shared-jdbc implementing read-write separation
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325597729&siteId=291194637
Recommended
Ranking