ShardingSphere-JDBC read and write separation

Explanation: This is mainly to read the documents of the shardingSphere course of Mr. Shang Silicon Valley Huanhuan, and record it. On the basis of her master-slave construction, I plan to implement a set of mysql master-slave + redis sentinel cluster + canal + local cache. Sort these out together.
This blog is based on the previous one, and it is written next. If you need to build a mysql master-slave, you can refer to the previous one

Build mysql master-slave based on docker

1. Create a SpringBoot program

1.1. Create a project

Project Type: Spring Initializr

SpringBoot scaffolding: http://start.aliyun.com

Project name: sharding-jdbc-demo

SpringBoot version: 2.3.7.RELEASE

1.2. Add dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
        <version>5.1.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

1.3. Create entity class

package com.atguigu.shardingjdbcdemo.entity;

@TableName("t_user")
@Data
public class User {
    
    
    @TableId(type = IdType.AUTO)
    private Long id;
    private String uname;
}

1.4. Create Mapper

package com.atguigu.shardingjdbcdemo.mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    
}

1.5. Configure read-write separation

application.properties:

# 应用名称
spring.application.name=sharging-jdbc-demo
# 开发环境设置
spring.profiles.active=dev
# 内存模式
spring.shardingsphere.mode.type=Memory

# 配置真实数据源
spring.shardingsphere.datasource.names=master,slave1,slave2

# 配置第 1 个数据源
spring.shardingsphere.datasource.master.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.jdbc-url=jdbc:mysql://192.168.100.201:3306/db_user
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=123456

# 配置第 2 个数据源
spring.shardingsphere.datasource.slave1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.slave1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave1.jdbc-url=jdbc:mysql://192.168.100.201:3307/db_user
spring.shardingsphere.datasource.slave1.username=root
spring.shardingsphere.datasource.slave1.password=123456

# 配置第 3 个数据源
spring.shardingsphere.datasource.slave2.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.slave2.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave2.jdbc-url=jdbc:mysql://192.168.100.201:3308/db_user
spring.shardingsphere.datasource.slave2.username=root
spring.shardingsphere.datasource.slave2.password=123456

# 读写分离类型,如: Static,Dynamic
spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.type=Static
# 写数据源名称
spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.props.write-data-source-name=master
# 读数据源名称,多个从数据源用逗号分隔
spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.props.read-data-source-names=slave1,slave2

# 负载均衡算法名称
spring.shardingsphere.rules.readwrite-splitting.data-sources.myds.load-balancer-name=alg_round

# 负载均衡算法配置
# 负载均衡算法类型
spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_round.type=ROUND_ROBIN
spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_random.type=RANDOM
spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.type=WEIGHT
spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.props.slave1=1
spring.shardingsphere.rules.readwrite-splitting.load-balancers.alg_weight.props.slave2=2

# 打印SQl
spring.shardingsphere.props.sql-show=true

2. Test

2.1, read and write separation test

package com.atguigu.shardingjdbcdemo;

@SpringBootTest
class ReadwriteTest {
    
    

    @Autowired
    private UserMapper userMapper;

    /**
     * 写入数据的测试
     */
    @Test
    public void testInsert(){
    
    

        User user = new User();
        user.setUname("张三丰");
        userMapper.insert(user);
    }

}

2.2. Transaction test

In order to ensure the transaction consistency between master and slave databases and avoid cross-service distributed transactions, ShardingSphere-JDBC is used 主从模型中,事务中的数据读写均用主库.

  • Do not add @Transactional: insert operates on the master library, select operates on the slave library
  • Add @Transactional: both insert and select operate on the main library
  • **Note: **The @Transactional annotation in the JUnit environment will roll back the transaction by default (even if @Rollback is not annotated, the transaction will be rolled back)
/**
     * 事务测试
     */
@Transactional//开启事务
@Test
public void testTrans(){
    
    

    User user = new User();
    user.setUname("铁锤");
    userMapper.insert(user);

    List<User> users = userMapper.selectList(null);
}

2.3. Load balancing test


/**
     * 读数据测试
     */
@Test
public void testSelectAll(){
    
    
    List<User> users = userMapper.selectList(null);
    List<User> users = userMapper.selectList(null);//执行第二次测试负载均衡
    users.forEach(System.out::println);
}

You can also test load balancing in web requests

package com.atguigu.shardingjdbcdemo.controller;

@RestController
@RequestMapping("/userController")
public class UserController {
    
    

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试负载均衡策略
     */
    @GetMapping("selectAll")
    public void selectAll(){
    
    
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }
}

Guess you like

Origin blog.csdn.net/qq_35771266/article/details/128101972