sharding-jdbc-spring-boot-starter is the easiest to use

foreword

There are already a lot of use of sharding-jdbc on the Internet, but many of them are copied and copied, and the words are not particularly complete. The author originally wanted to run and try the effect when he had nothing to do, but he found some documents. It is very clear. And many of them use sharding-jdbc-core, but we should rarely use spring mvc development now, most of them are developed by springboot, so we still want to use the starter method. After continuous trial and error, build the simplest test case with the least configuration code. If it helps, please give a thumbs up.

1. Introduce dependencies

  1. mybatis-spring-boot-starter
  2. sharding-jdbc-spring-boot-starter
  3. druid
<!-- 核心依赖-mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<!-- 核心依赖-mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- 核心依赖-sharding-jdbc -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.1</version>
</dependency>
<!-- 核心依赖-数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.22</version>
</dependency>

It should be noted that the druid database connection pool used here must use this. If the starter reference of druid is used, the automatically assembled classes need to be excluded, otherwise the data source will be automatically built, resulting in failure.

Second, the database table structure

What is demonstrated here is sub-database and sub-table, so there will be two databases, and each database has two tables, the table structure is the same
db1: t_user_1 , t_user_2
db2: t_user_1 , t_user_2

database structure
The table structure is:
Table Structure

3. Configuration file



# 应用服务 WEB 访问端口
server:
  port: 8080

  # 应用名称
spring:
  application:
    name: sharding-jdbc-test
  shardingsphere:
    # 是否打印sql
    props:
      sql:
        show: true
    datasource:
      # 有几个库
      names: db1,db2
      # 库1 的配置
      db1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db1?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
        username: root
        password: 123456
      # 库2 的配置
      db2:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db2?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
        username: root
        password: 123456
    sharding:
      # 默认的库
      default-data-source-name: db1
      # 绑定的表 不配置也没找出啥问题
      binding-tables: t_user
      # 配置表的分片规则
      tables:
        # 指定某个表的分片配置
        t_user:
          # 这个配置是告诉sharding有多少个库和多少个表
          actual-data-nodes: db$->{
    
    1..2}.t_user_$->{
    
    1..2}
          #分库策略
          database-strategy:
            # 行表达式模式
            inline:
              # 选择需要分库的字段,根据那个字段进行区分
              sharding-column: age
              # 表达式,分库的算法,这个是通过年龄取模然后决定落到哪个库
              algorithm-expression: db$->{
    
    age % 2 + 1}
          # 主键生成策略(如果是自动生成的,在插入数据的sql中就不要传id,null也不行,直接插入字段中就不要有主键的字段)
          key-generator: 
            # 对应的数据库表的主键
            column: id
            # 生成方式, 雪花模式
            type: SNOWFLAKE
          # 配置表分片策略
          table-strategy:
            # 行表达式
            inline:
              # 配置表分片的字段
              sharding-column: id
              # 配置表分片算法
              algorithm-expression: t_user_$->{
    
    id % 2 +1}


mybatis.configuration.map-underscore-to-camel-case: true

Fourth, the code configuration

In fact, so far, the configuration of sharding-jdbc has been completed, and the rest is the configuration of mybatis, which can be the same as normal CURD

mapper interface

public interface UserMapper {
    
    
    
    /** 如果是主键自动生成的,切记不要传入id,否则会报错 */
    @Insert("insert into t_user(name,age) values(#{name},#{age})")
    void insert(UserModel user);


    @Select("select * from t_user")
    List<UserModel> selectAll();


    @Select("select * from t_user where name like #{name}")
    List<UserModel> selectLike(String name);


    @Select("select * from t_user where name like #{name} limit 1")
    List<UserModel> selectLikePage(String name);

}

model

@Data
public class UserModel {
    
    
    
    private Long id;

    private String name;

    private Integer age;
}

Startup class and test method

@SpringBootApplication
@MapperScan(basePackages = "com.xxx.shard.shardingjdbctest.mapper")
public class ShardingJdbcTestApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(ShardingJdbcTestApplication.class, args);
    }
    
    @RestController
    class TestController{
    
    
        
        @Resource
        UserMapper userMapper;

        @GetMapping("/add")
        public Object add(){
    
    

            UserModel model = new UserModel();
//            model.setId(2);
            model.setName("test2");
            model.setAge(1);
            userMapper.insert(model);
            return "ok";
        }


        @GetMapping("/list")
        public Object list(){
    
    

            return userMapper.selectAll();
        }


        @GetMapping("/like")
        public Object like(){
    
    

            return userMapper.selectLike("%2%");
        }

        @GetMapping("/page")
        public Object page(){
    
    

            return userMapper.selectLikePage("%2%");
        }

    }
}

Overall project structure

V. Summary

The test case here is the simplest configuration of sub-database and sub-table. It is mainly for beginners to experience the effect when using it. Only after the entry is built, the company projects that follow can be configured bit by bit.

Guess you like

Origin blog.csdn.net/weixin_33613947/article/details/121124755