=2;
案例说明:
上面创建的表,虽然是goods_0
和goods_1
,但案例中Pojo
用到了逻辑表,如下:
@Data
@TableName(value = "goods") //这里用的是逻辑表
public class Goods {
@TableId(value = "id",type = IdType.INPUT)
private Long id;
@TableField(value = "goods_name")
private String goodsName;
@TableField(value = "type")
private Long type;
}
处理上面之外,案例提供了三个方法:
package com.execise.controller;
import com.execise.domain.Goods;
import com.execise.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@GetMapping
public List<Goods> list(){
return goodsService.list();
}
//@GetMapping("/{id}")
public Goods getOne(@PathVariable int id){
return goodsService.getById(id);
}
@GetMapping("/add/{goodsName}/{type}")
public String add(@PathVariable String goodsName, @PathVariable int type){
Goods goods = new Goods();
goods.setGoodsName(goodsName);
goods.setType(type);
goodsService.save(goods);
return "添加成功!";
}
}
分库案例
我们使用ShadingJDBC
实现数据分片,将一部分数据添加到sd1
一部分数据添加到sd2
中,一部分数据添加到goods_0
中,一部分数据添加到goods_1
中。
我们先实现将一部分数据添加到sd1
中,一部分数据添加到sd2
中,这种操作就是分库操作,分库操作可以减少每个数据库中存储的数据,当数据少了,查询的时候,单台数据库查找的数据量就减少了,从而加速了每台数据库查找速度。
分库策略
分库策略如上图:
#求余算法
添加数据的时候,我们由于只有2台数据库,我们可以根据某个字段 column%2 求余,来确定数据存入哪个数据库,这种算法是很常规的算法。
#案例求余
在案例中,我们可以把type作为求余的column,用type%2的余数作为数据库的下标,这种算法是非常简单的。
分库配置
修改application.yml
,配置分库策略,配置如下:
spring:
shardingsphere:
# 数据源配置
datasource:
# 名称随意,但必须唯一
names: ds1,ds2
# 这里的名称需要在datasource.names中存在
ds1:
# jdbc需要配置连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/sd1?serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useSSL=false
ds2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/sd2?serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useSSL=false
# 分片配置
sharding:
# 需要分片的表配置
tables:
# 需要分片的表名,逻辑名,随意
goods:
# 数据节点配置ds${}组成上面names中的数据源名称, 1..2代表 1到2之间的数值
# 数据库中表的语法:schema.表名 = database.表名
actualDataNodes: ds${1..2}.goods
# 分库策略
databaseStrategy:
# 使用inline分片算法
inline:
# 分片键 为表中某个字段
shardingColumn: type
# 具体分片时的表达式
algorithmExpression: ds${type % 2 + 1}
props:
# 是否打印sql
sql.show: true
logging:
pattern:
console: '%d{HH:mm:ss} %msg %n\'
level:
root: info
com:
execise: debug
分表案例
基于上面的案例,我们再实现分表操作,一部分数据存入goods_0
,一部分数据存入goods_1
。
分表策略
如上图:
#分表策略
我们需要将数据存入到goods_0或者goods_1中,也可以采用求余法,采用id作为求余的列, id%