关键词

Sharding-JDBC自动实现MySQL读写分离的示例代码

下面我来详细讲解一下“Sharding-JDBC自动实现MySQL读写分离的示例代码”的完整攻略。

什么是Sharding-JDBC

Sharding-JDBC是一个基于JDBC的轻量级数据库中间件,能够完成Java应用程序中的数据分片,水平分片和读写分离等功能。

实现MySQL读写分离的步骤

步骤一:添加依赖

在项目的pom.xml文件中添加以下依赖:

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

步骤二:配置数据源

application.yml文件中配置数据源,如下所示:

spring:
  datasource:
    names: ds0,ds1
    ds0:
      url: jdbc:mysql://127.0.0.1:3306/test0?useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC
      username: root
      password: root
    ds1:
      url: jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC
      username: root
      password: root

步骤三:添加Sharding-JDBC配置

application.yml文件中添加Sharding-JDBC配置,如下所示:

spring:
  shardingsphere:
    datasource:
      names: myshard
      myshard:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306
        username: root
        password:
        hikari:
          minimum-idle: 5
          maximum-pool-size: 50
    sharding:
      tables:
        user:
          actual-data-nodes: myshard.user_${0..1}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: user_${id % 2}
          key-generator:
            column: id
            type: SNOWFLAKE
        order:
          actual-data-nodes: myshard.order_${0..1}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: order_${id % 2}
          key-generator:
            column: id
            type: SNOWFLAKE
      default-database-strategy:
        inline:
          sharding-column: ds_name
          algorithm-expression: ds$->{id % 2}
      default-table-strategy:
        none:

步骤四:添加Mapper和Service

添加UserMapper和UserService,如下所示:

@Mapper
public interface UserMapper {
    @Insert("INSERT INTO user (name, age, gender) VALUES (#{name},#{age},#{gender})")
    int insert(User user);

    @Select("SELECT * from user WHERE id = #{id}")
    User getById(long id);
}
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    @Transactional
    public void addUser(User user){
        userMapper.insert(user);
    }

    public User getUserById(long id){
        return userMapper.getById(id);
    }
}

步骤五:测试读写分离

在测试类中添加以下测试代码,测试Sharding-JDBC是否能够实现MySQL读写分离:

@SpringBootTest
class ShardingJdbcApplicationTests {
    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        User user = new User();
        user.setName("Tom");
        user.setAge(18);
        user.setGender("male");
        userService.addUser(user);

        User user1 = userService.getUserById(1);
        System.out.println(user1);
    }
}

以上代码就是Sharding-JDBC自动实现MySQL读写分离的示例代码。通过配置Sharding-JDBC实现数据分片和读写分离,从而提高数据库的读写性能和吞吐量。

示例

示例一:测试读写分离

在Sharding-JDBC自动实现MySQL读写分离的示例代码中,添加以下测试代码,测试Sharding-JDBC是否能够实现MySQL读写分离:

@SpringBootTest
class ShardingJdbcApplicationTests {
    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        User user = new User();
        user.setName("Tom");
        user.setAge(18);
        user.setGender("male");
        userService.addUser(user);

        User user1 = userService.getUserById(1);
        System.out.println(user1);
    }
}

以上代码执行后,会向数据库插入一条记录,并从数据库中查询出这条记录。

示例二:测试分片策略

在Sharding-JDBC自动实现MySQL读写分离的示例代码中,修改application.yml文件中的分片策略,如下所示:

spring:
  shardingsphere:
    datasource:
      names: myshard
      myshard:
        ...
        hikari:
          minimum-idle: 5
          maximum-pool-size: 50
    sharding:
      tables:
        user:
          actual-data-nodes: myshard.user${0..1}.user_${0..1}
          table-strategy:
            complex:
              sharding-columns: id,gender
              algorithm-class-name: com.example.demo.algorithm.ModuloShardingAlgorithm
          key-generator:
            column: id
            type: SNOWFLAKE
      ...

同时,修改ModuloShardingAlgorithm类的具体实现,如下所示:

public class ModuloShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        Set<String> result = new HashSet<>();
        for (Long value : shardingValue.getColumnNameAndShardingValuesMap().get("gender")) {
            String suffix = value % 2 + "_" + shardingValue.getColumnNameAndShardingValuesMap().get("id").iterator().next() % 2;
            for (String name : availableTargetNames) {
                if (name.endsWith(suffix)) {
                    result.add(name);
                }
            }
        }
        return result;
    }
}

以上修改的分片策略是基于id和gender两个字段进行分片,其中id字段按照2个一组进行分片,gender字段按照值的模2进行分片。

修改完成后,重新执行测试类中的测试方法,验证Sharding-JDBC是否能够按照新的分片策略进行数据分片。

本文链接:http://task.lmcjl.com/news/13137.html

展开阅读全文