Spring整合ShardingJDBC实现MySQL读写分离

  1. 首先需要搭建MySQL读写分离的服务器环境

    1. 安装MySQL参见 CentOS下安装MySQL5.7(图文)
    2. 搭建MySQL读写分离参见 ContOS下搭建MySQL主从复制
  2. 新建一个Maven项目spring-sharding-masterslave

  3. 引入相关的依赖

    
    <dependency>
        <groupId>org.apache.shardingspheregroupId>
        <artifactId>sharding-jdbc-coreartifactId>
        <version>4.0.0-RC1version>
    dependency>
    
    
    <dependency>
        <groupId>org.apache.shardingspheregroupId>
        <artifactId>sharding-jdbc-spring-namespaceartifactId>
        <version>4.0.0-RC1version>
    dependency>
    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>5.1.6.RELEASEversion>
    dependency>
    
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.47version>
    dependency>
    
    
    <dependency>
        <groupId>com.zaxxergroupId>
        <artifactId>HikariCPartifactId>
        <version>3.2.0version>
    dependency>
    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>5.1.6.RELEASEversion>
    dependency>
    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
    
    <dependency>
          <groupId>ch.qos.logbackgroupId>
          <artifactId>logback-classicartifactId>
          <version>1.2.3version>
    dependency>
    
  4. 在resources添加Spring的配置文件applicationContext.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:master-slave="http://shardingsphere.apache.org/schema/shardingsphere/masterslave"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://shardingsphere.apache.org/schema/shardingsphere/encrypt http://shardingsphere.apache.org/schema/shardingsphere/encrypt/encrypt.xsd http://shardingsphere.apache.org/schema/shardingsphere/sharding http://shardingsphere.apache.org/schema/shardingsphere/sharding/sharding.xsd http://shardingsphere.apache.org/schema/shardingsphere/masterslave http://shardingsphere.apache.org/schema/shardingsphere/masterslave/master-slave.xsd">
    
        
        <bean id="ds0" class="com.zaxxer.hikari.HikariDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="jdbcUrl" value="jdbc:mysql://192.168.9.174:3306/test?useSSL=false"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        bean>
    
        
        <bean id="ds1" class="com.zaxxer.hikari.HikariDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="jdbcUrl" value="jdbc:mysql://192.168.9.184:3306/test?useSSL=false"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        bean>
    
        
        <master-slave:data-source id="msDataSource" master-data-source-name="ds0" slave-data-source-names="ds0,ds1">
            <master-slave:props>
                <prop key="sql.show">trueprop>
            master-slave:props>
        master-slave:data-source>
    beans>
    

    此时使用ShardingJDBC搭建读写分离的配置已经完成

  5. 在test下新建一个测试类ShardingTest,先测试数据写入的操作

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.annotation.Resource;
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class ShardingTest {
    
        @Resource(name = "msDataSource")
        private DataSource dataSource;
    
        /**
         * 利用ShardingJDBC的读写分离进行写入数据的操作
         * @throws SQLException
         */
        @Test
        public void testInsert() throws SQLException {
            Connection connection = dataSource.getConnection();
            String sql = "INSERT INTO t_user (id, username, password, birthday) VALUES (null, 'test insert', '134', '2019-07-23 14:52:05')";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
            preparedStatement.close();
            connection.close();
        }
    
    }
    
    

    通过查看日志,我们发现不管进行多少次的写入操作,一直使用的是ds0数据库进行写入操作,如下图

    Spring整合ShardingJDBC实现MySQL读写分离_第1张图片

  6. 在test下新建一个测试类ShardingTest,测试数据读取的操作

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.annotation.Resource;
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class ShardingTest {
    
        @Resource(name = "msDataSource")
        private DataSource dataSource;
    
        /**
         * 利用ShardingJDBC的读写分离进行数据读取的操作
         * @throws SQLException
         */
        @Test
        public void selectTest() throws SQLException {
            Connection connection = dataSource.getConnection();
            String sql = "select * from t_user";
            for (int i = 0; i < 10; i++) {
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.executeQuery();
                preparedStatement.close();
            }
            connection.close();
        }
    }
    
    

    通过查看日志,我们发现随着不同次数的查询,执行查询的数据库在ds0和ds1之间一直切换,如下图

    Spring整合ShardingJDBC实现MySQL读写分离_第2张图片

  7. 至此,Spring整合ShardingJDBC实现读写分离的功能已经完全实现。

  8. 相关的测试代码详见 Spring整合ShardingJDBC实现MySQL读写分离演示代码

你可能感兴趣的:(MySQL)