springboot整合shardingsphere JDBC,雪花算法

springBoot 版本 2.7.3
shardingsphere版本5.2.0

文章目录

  • 依赖
  • 数据准备
  • application.yaml编写
  • model
  • repository
  • test

依赖

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        <dependency>
            <groupId>org.apache.shardingspheregroupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starterartifactId>
            <version>5.2.0version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

数据准备

两个数据库,每个库中一张表,也可以多张,这里演示一张的情况

create table hello_spring_boot.sys_user
(
    id             bigint unsigned                     not null
        primary key,
    user_name      varchar(20)                         not null,
    group_id       bigint unsigned                     not null,
    password       varchar(50)                         not null,
    phone_number   varchar(50)                         not null,
    c_time         timestamp default CURRENT_TIMESTAMP null,
    u_time         timestamp default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP
);

create table hello_spring_boot_2.sys_user
(
    id             bigint unsigned                     not null
        primary key,
    user_name      varchar(20)                         not null,
    group_id       bigint unsigned                     not null,
    password       varchar(50)                         not null,
    phone_number   varchar(50)                         not null,
    c_time         timestamp default CURRENT_TIMESTAMP null,
    u_time         timestamp default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP
);

application.yaml编写

# shardingsphere读写分离。分片篇日志文档 https://shardingsphere.apache.org/document/legacy/3.x/document/cn/manual/sharding-jdbc/configuration/config-yaml/
spring:
  shardingsphere:
    datasource: # 配置数据源
      names: ds_0, ds_1 # 分库的逻辑库名,可配置多个
      ds_0: # 逻辑库名
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        jdbcUrl: jdbc:mysql://localhost:3306/hello_spring_boot?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
      ds_1:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        jdbcUrl: jdbc:mysql://localhost:3306/hello_spring_boot_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
    props:
      sql:
        show: true # 开启sql日志输出
    rules:
      sharding:
        sharding-algorithms:
          database-inline:
            type: INLINE
            props:
              # 分片算法的行表达式(算法自行定义,此处为方便演示效果)
              algorithm-expression: ds_$->{id % 2}
          table-inline:
            type: INLINE
            props:
              # 分片算法的行表达式
              algorithm-expression: sys_user
        default-key-generate-strategy:
          column: id
          key-generator-name: snowflake
        key-generators:
          snowflake:
            type: SNOWFLAKE
            props:
              worker-id: 1
        tables:
          sys_user:
            actual-data-nodes: ds_${0..1}.sys_user
            database-strategy:
              standard:
                shardingColumn: id
                shardingAlgorithmName: database-inline
                # 分表策略
            table-strategy:
              standard:
                # 分片列名称
                sharding-column: id
                # 分片算法名称
                sharding-algorithm-name: table-inline
            keyGeneratorColumnName: id
            keyGenerateStrategy: # 分布式序列策略
              column: id # 自增列名称,缺省表示不使用自增主键生成器
              keyGeneratorName: snowflake
              props:
                worker-id: 1


model

@Data
@Entity
@Table(name = "sys_user")
public class SysUser {

    @Id
    //要指定strategy = GenerationType.IDENTITY,不然雪花算法不生效
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_name", length = 20)
    private String userName;

    private Long groupId;

    private String password;

    private String phoneNumber;

    private Date cTime;

    private Date uTime;
}

repository

public interface SysUserRepository extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {

}

test

@SpringBootTest
class ShardingSphereApplicationTests {

    @Autowired
    SysUserRepository sysUserRepository;


    @Test
    void contextLoads() {
        for (long i = 0; i < 10L; i++) {
            SysUser user = new SysUser();
            user.setUserName("sharding");
            user.setGroupId(1L);
            user.setPassword("123456");
            user.setPhoneNumber("123456");
            sysUserRepository.save(user);
        }
    }
}

shardingsphere配置文件参考: https://shardingsphere.apache.org/document/legacy/3.x/document/cn/manual/sharding-jdbc/configuration/config-yaml/

源码地址:https://github.com/googalAmbition/hello-spring-boot/tree/main/24-sharding-sphere

你可能感兴趣的:(springboot,Jpa,spring,boot,java,spring,数据库,shardingsphere)