最近公司项目要对数据库表做分表功能,今天弄了一天,总算把demo运行起来,存取都没问题了,在这里做下记录,希望能给有需要的小伙伴一点点帮助吧!
项目架构:springboot2.3 + mybatis + sharding jdbc +mysql
sharding jdbc :用来实现数据库分库、分表 ,推介去官网看看https://shardingsphere.apache.org/index_zh.html
其它就不做介绍了很基础的东西
1.先来张项目架构图
2. maven的pom文件依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--热部署自启动工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--分库分表工具-->
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
注意sharding jdbc依赖这里有点坑,管网上给的依赖maven没办法下载
3.application.properties配置文件内容
#boot内置tomcat端口
server.port=8080
#mybatis映射文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
#配置sharding数据源
#这里是给取的别名,下面配置要使用
sharding.jdbc.datasource.names=ds
#指定数据库连接池
sharding.jdbc.datasource.ds.type=com.alibaba.druid.pool.DruidDataSource
#mysql数据库连接驱动,注意我这里是用的mysql8+的,低版本的是com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.ds.url=jdbc:mysql://localhost:3306/baobiao_pc?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
sharding.jdbc.datasource.ds.username=root
sharding.jdbc.datasource.ds.password=123456
#分表相关配置 note是我数据库要分表的表前缀,ds.note$->{0..1}这里表示ds数据库中的note0,note1两个表
sharding.jdbc.config.sharding.tables.note.actual-data-nodes=ds.note$->{0..1}
# 配置分表策略
sharding.jdbc.config.sharding.tables.note.table-strategy.inline.sharding-column=id
# 配置分片算法
sharding.jdbc.config.sharding.tables.note.table-strategy.inline.algorithm-expression=note$->{id % 2}
sharding.jdbc.config.sharding.tables.note.key-generator-column-name=id
# 打印执行的数据库以及语句
sharding.jdbc.config.props..sql.show=true
#spring.main.allow-bean-definition-overriding=true
4. 然后是id生成工具类,分表没办法使用主键自动生成
public class IdWorker {
//下面两个每个5位,加起来就是10位的工作机器id
private long workerId; //工作id
private long datacenterId; //数据id
//12位的***
private long sequence;
public IdWorker(long workerId, long datacenterId, long sequence){
// sanity check for workerId
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
}
System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
//初始时间戳
private long twepoch = 1288834974657L;
//长度为5位
private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
//最大值
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
//***id长度
private long sequenceBits = 12L;
//***最大值
private long sequenceMask = -1L ^ (-1L << sequenceBits);
//工作id需要左移的位数,12位
private long workerIdShift = sequenceBits;
//数据id需要左移位数 12+5=17位
private long datacenterIdShift = sequenceBits + workerIdBits;
//时间戳需要左移位数 12+5+5=22位
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
//上次时间戳,初始值为负数
private long lastTimestamp = -1L;
public long getWorkerId(){
return workerId;
}
public long getDatacenterId(){
return datacenterId;
}
public long getTimestamp(){
return System.currentTimeMillis();
}
//下一个ID生成算法
public synchronized long nextId() {
long timestamp = timeGen();
//获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常
if (timestamp < lastTimestamp) {
System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
//获取当前时间戳如果等于上次时间戳(同一毫秒内),则在***加一;否则***赋值为0,从0开始。
sequence = (sequence + 1) & sequenceMask;
/*if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}*/
//将上次时间戳值刷新
lastTimestamp = timestamp;
/**
* 返回结果:
* (timestamp - twepoch) << timestampLeftShift) 表示将时间戳减去初始时间戳,再左移相应位数
* (datacenterId << datacenterIdShift) 表示将数据id左移相应位数
* (workerId << workerIdShift) 表示将工作id左移相应位数
* | 是按位或运算符,例如:x | y,只有当x,y都为0的时候结果才为0,其它情况结果都为1。
* 因为个部分只有相应位上的值有意义,其它位上都是0,所以将各部分的值进行 | 运算就能得到最终拼接好的id
*/
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
//获取时间戳,并与上次时间戳比较
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
//获取系统时间戳
private long timeGen(){
return System.currentTimeMillis();
}
//---------------测试---------------
public static void main(String[] args) {
IdWorker worker = new IdWorker(1,1,1);
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(worker.nextId());
}
}
}
5.然后是springboot启动类
package com.sbkj;
import com.sbkj.util.IdWorker;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
@SpringBootApplication
@MapperScan("com.sbkj.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
/**
* 实例id生成工具类,交由spring管理
* @return
*/
@Bean
public IdWorker getIdWorker(){
return new IdWorker(1,1,1);
}
}
6.最后是controller,没什么业务就没写service了,实体和dao(mapper)就用的mybatis自动生成的就不贴出来了
package com.sbkj.controller;
import com.sbkj.entity.Note;
import com.sbkj.mapper.NoteMapper;
import com.sbkj.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.List;
@RestController
public class TestController {
@Autowired
NoteMapper noteMapper;
@Autowired
IdWorker idWorker;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Note index(Note note){
note.setId(idWorker.nextId());//主键生成
noteMapper.insert(note);
return note;
}
@RequestMapping(value = "/book", method = RequestMethod.GET)
public List<Note> getItems(){
return noteMapper.getNoteList();
}
@RequestMapping(value = "/getNote")
public Note getNote(Long id){
return noteMapper.selectByPrimaryKey(id);
}
}
最最后献上运行效果图,添加了2条数据,通过配置的id分片算法分别添加进去了
在来张取数据的,可以看到2张表都查询了