文章目录
前言
本文主要介绍SpringBoot集成sharding-jdbc,使用sharding-jdbc分表相关功能使用。
一、sharding-jdbc是什么?
sharding-jdbc可以帮助我们。shardingSphere官网
二、使用步骤
1、添加测试库表
CREATE TABLE `t_user_0` (
`ID` bigint(20) NOT NULL COMMENT '分布式ID',
`COMPANY_ID` int(50) NOT NULL COMMENT '公司ID',
`NAME` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT '用户姓名',
`AGE` int(3) DEFAULT NULL COMMENT '年龄',
`ADDRESS` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '地址',
`CREATE_TIME` datetime DEFAULT NULL,
`CREATE_USER` varchar(255) DEFAULT NULL,
`UPDATE_TIME` datetime DEFAULT NULL,
`UPDATE_USER` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='测试表';
CREATE TABLE `t_user_1` (
`ID` bigint(20) NOT NULL COMMENT '分布式ID',
`COMPANY_ID` int(50) NOT NULL COMMENT '公司ID',
`NAME` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT '用户姓名',
`AGE` int(3) DEFAULT NULL COMMENT '年龄',
`ADDRESS` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '地址',
`CREATE_TIME` datetime DEFAULT NULL,
`CREATE_USER` varchar(255) DEFAULT NULL,
`UPDATE_TIME` datetime DEFAULT NULL,
`UPDATE_USER` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='测试表';
2.引入maven依赖
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--pageHelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</exclusion>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<!-- sharding-jdbc -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.1.1</version>
</dependency>
3.配置数据源及分表策略
spring.shardingsphere.datasource.names=ds0
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://x.x.x.x:3306/saas_health?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=ds0.t_user_$->{0..1}
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=COMPANY_ID
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user_$->{COMPANY_ID % 2}
spring.shardingsphere.props.sql.show=true
4.创建实体类及Service
这里只提供实体类,service可以参考本人关于mybatis-plus使用的博客。
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
/**
* All rights Reserved, Designed By www.biosan.cn
*
* @Description:
* @author: 牛二强
* @date: 2021/2/2 14:37
*/
@Data
@TableName("t_user")
public class TestUser {
private Long id;
private Long companyId;
private String name;
private Integer age;
private String address;
private String createUser;
private Date createTime;
private String updateUser;
private Date updateTime;
public TestUser() {
}
public TestUser(Long companyId, String name, Integer age, String address) {
this.companyId = companyId;
this.name = name;
this.age = age;
this.address = address;
}
}
5.录入数据
@Test
public void testUser1(){
TestUser user = new TestUser(27L,"jack",18,"杭州市");
user.setCreateUser("NEQ");
user.setCreateTime(new Date());
testUserService.save(user);
}

6.遇到的问题
- mysql连接版本问题
Caused by: java.sql.SQLException: Table name pattern can not be NULL or empty.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:545)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
这里的版本如果使用6.x版本就会出现上面问题,替换为5.x就没问题了
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
- druid包依赖问题
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/DruidDataSourceAutoConfigure.class]: Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
这里不能依赖这个starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
需要修改为原始druid包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
- sharding-jdbc依赖引入错误
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'io.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration': Initialization of bean failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
去除下面两个依赖
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>3.1.0</version>
</dependency>
- dataSource is already bound错误,这个问题之前出现过,但是目前复现不出来了。按照上面的配置,应该不会出现了。
7.多数据源配置及默认数据源配置
spring.profiles.active=test
server.port=9997
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jackson.dateFormat=yyyy-MM-dd HH:mm:ss
spring.jackson.timeZone=GMT+0
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.max-file-size=10MB
spring.cloud.loadbalancer.ribbon.enabled=false
spring.application.name=games-service
eureka.client.fetch-registry=true
eureka.instance.prefer-ip-address=true
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=15
eureka.instance.non-secure-port=${server.port}
spring.shardingsphere.datasource.names=ds0,ds1
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://172.30.10.43:3306/sdp_account?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
spring.shardingsphere.datasource.ds0.username=test
spring.shardingsphere.datasource.ds0.password=password
#默认数据源,如果部分表不进行分表,则加此配置
spring.shardingsphere.sharding.default-data-source-name=ds1
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=ds0.t_user_$->{0..8}
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=app_id
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user_$->{app_id % 9}
spring.shardingsphere.sharding.tables.t_user.key-generator.column=id
spring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKE
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://172.30.10.43:3306/sdp_games?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
spring.shardingsphere.datasource.ds1.username=test
spring.shardingsphere.datasource.ds1.password=password
spring.shardingsphere.sharding.tables.t_app_user_detail.actual-data-nodes=ds1.t_app_user_detail_$->{0..8}
spring.shardingsphere.sharding.tables.t_app_user_detail.table-strategy.inline.sharding-column=app_id
spring.shardingsphere.sharding.tables.t_app_user_detail.table-strategy.inline.algorithm-expression=t_app_user_detail_$->{app_id % 9}
spring.shardingsphere.sharding.tables.t_app_user_detail.key-generator.column=id
spring.shardingsphere.sharding.tables.t_app_user_detail.key-generator.type=SNOWFLAKE
spring.shardingsphere.props.sql.show=true
总结
以上就是今天要讲的内容,本文仅仅简单介绍了sharding-jdbc的分表使用,而sharding-jdbc还提供分库、读写分离、分布式事务等一系列功能,本文就不做过多介绍,感兴趣可以到官网查看使用手册学习,这里给出链接:官网手册。
本文详述了SpringBoot如何集成sharding-jdbc进行分表操作,包括添加测试库表、引入依赖、配置数据源和分表策略、创建实体类与Service、解决遇到的mysql连接版本、druid包依赖和数据源已绑定等问题,以及多数据源配置。
6351

被折叠的 条评论
为什么被折叠?



