springboot:2.1.9
cloud:Greenwich.SR2
sharding:4.0.0-RC1
本文的主要目的是通过shardingsphere对同一库中的数据进行分表处理。
1:首先在数据库中新建3张表tab_user0、tab_user1、tab_user2
2:再对配置文件进行响应修改
pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.9.RELEASE
com.sharding
stuTab
0.0.1-SNAPSHOT
stuTab
Demo project for Spring Boot
1.8
1.1.16
Greenwich.SR2
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
com.alibaba
druid-spring-boot-starter
${druid}
org.apache.shardingsphere
sharding-jdbc-spring-boot-starter
4.0.0-RC1
org.apache.shardingsphere
sharding-jdbc-spring-namespace
4.0.0-RC1
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
cn.hutool
hutool-all
5.3.2
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
2.1.1.RELEASE
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
stuTab #项目名称
application
server.port=8066
spring.shardingsphere.datasource.names=master #设置库的别名
# 数据源
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://xxx:3306/xxx?characterEncoding=utf-8
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=welcome123
#数据分表规则
#指定所需分的表
spring.shardingsphere.sharding.tables.tab_user.actual-data-nodes=master.tab_user$->{0..2}
#指定主键
spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.sharding-column=id
#分表规则为主键除以3取模
spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.algorithm-expression=tab_user$->{id % 3}
#设置mybatis相关信息
mybatis.typeAliasesPackage=com.sharding.stuTab.pojo
mybatis.mapperLocations=classpath:mapper/*.xml
#打印sql
spring.shardingsphere.props.sql.show=true
spring.main.allow-bean-definition-overriding=true
#设置springcloud相关
spring.application.name=stuTab
spring.cloud.nacos.discovery.server-addr=10.241.95.109:8848,10.241.95.110:8848,10.241.95.111:8848
spring.cloud.nacos.discovery.cluster-name=stuTab
spring.cloud.nacos.discovery.service=stuTab
spring.cloud.nacos.discovery.register-enabled=true
spring.cloud.nacos.discovery.namespace=public
spring.cloud.nacos.discovery.heart-beat-timeout=5000
nacos.config.server-addr=10.241.95.109:8848,10.241.95.110:8848,10.241.95.111:8848
3:配置相关完成后进入实际代码部分
启动类
package com.sharding.stuTab;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// cloud相关
@EnableDiscoveryClient
@Configuration
@SpringBootApplication
// 事务支持'
@EnableTransactionManagement
public class StuTabApplication {
public static void main(String[] args) {
SpringApplication.run(StuTabApplication.class, args);
}
}
接口类
package com.sharding.stuTab.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.sharding.stuTab.mapper.TabUserMapper;
import com.sharding.stuTab.pojo.TabUser;
import com.sharding.stuTab.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
protected static final Logger logger = LoggerFactory
.getLogger(UserController.class);
@Autowired
private UserService userService;
@Autowired
private TabUserMapper tabUserMapper;
/**
* 数据插入测试
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/dataInsert",method = RequestMethod.GET)
@ResponseBody
public JSONObject dataInsert(HttpServletRequest request, HttpServletResponse response ) throws Exception{
try {
ArrayList arr = new ArrayList<>();
for (int i=0;i<10;i++){
TabUser user = new TabUser();
arr.add(user);
}
userService.dataInsert(arr);
JSONObject jsonObject = new JSONObject();
jsonObject.put("return_code", "0");
jsonObject.put("operation","2");
return jsonObject;
} catch (Exception e) {
logger.error("UserController.dataInsert error", e);
return getBusinessJson("参数异常,请联系管理员");
}
}
/**
* 分页查询+数据删除
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/dataDelete",method = RequestMethod.GET)
@ResponseBody
public JSONObject dataDelete(HttpServletRequest request, HttpServletResponse response ) throws Exception{
try {
TabUser queryBean = new TabUser();
PageHelper.startPage(1,10);
List tabUsers = tabUserMapper.selectAll(queryBean);
PageInfo pageInfo = new PageInfo(tabUsers);
tabUsers = pageInfo.getList();
for (TabUser record : tabUsers){
tabUserMapper.deleteByPrimaryKey(record.getId());
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("return_code", "0");
jsonObject.put("operation","2");
jsonObject.put("data",tabUsers);
return jsonObject;
} catch (Exception e) {
logger.error("UserController.dataDelete error", e);
return getBusinessJson("参数异常,请联系管理员");
}
}
/**
* 数据全删
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/dataDestory",method = RequestMethod.GET)
@ResponseBody
public JSONObject dataDestory(HttpServletRequest request, HttpServletResponse response ) throws Exception{
try {
tabUserMapper.deleteAll();
JSONObject jsonObject = new JSONObject();
jsonObject.put("return_code", "0");
jsonObject.put("operation","2");
return jsonObject;
} catch (Exception e) {
logger.error("UserController.dataDestory error", e);
return getBusinessJson("参数异常,请联系管理员");
}
}
public JSONObject getBusinessJson(String msg){
if(Strings.isNullOrEmpty(msg)) {
msg="数据不合法,请重试!";
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("return_code", "-1002");
jsonObject.put("return_msg", msg);
return jsonObject;
}
}
服务层
package com.sharding.stuTab.service;
import com.sharding.stuTab.pojo.TabUser;
import java.util.List;
public interface UserService {
void dataInsert(List tabUserList);
}
package com.sharding.stuTab.service.impl;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.sharding.stuTab.mapper.TabUserMapper;
import com.sharding.stuTab.pojo.TabUser;
import com.sharding.stuTab.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private TabUserMapper tabUserMapper;
@Override
public void dataInsert(List tabUserList) {
// 通过雪花算法来获取主键
Snowflake snowflake = IdUtil.createSnowflake(1, 1);
for (TabUser user : tabUserList) {
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
user.setStatus(0);
user.setId(snowflake.nextId());
user.setAge(28);
user.setName("tudinle");
user.setSex("男");
tabUserMapper.insertSelective(user);
}
}
}
实体类
package com.sharding.stuTab.pojo;
import java.util.Date;
public class TabUser {
private Long id;
private String name;
private String sex;
private Integer age;
private Date createTime;
private Date updateTime;
private Integer status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
dao层
package com.sharding.stuTab.mapper;
import com.sharding.stuTab.pojo.TabUser;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface TabUserMapper {
int deleteByPrimaryKey(Long id);
int insert(TabUser record);
int insertSelective(TabUser record);
TabUser selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(TabUser record);
int updateByPrimaryKey(TabUser record);
List selectAll(TabUser record);
int deleteAll();
}
id, `name`, sex, age, create_time, update_time, `status`
delete from tab_user
where id = #{id,jdbcType=BIGINT}
insert into tab_user (id, `name`, sex,
age, create_time, update_time,
`status`)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP},
#{status,jdbcType=INTEGER})
insert into tab_user
id,
`name`,
sex,
age,
create_time,
update_time,
`status`,
#{id,jdbcType=BIGINT},
#{name,jdbcType=VARCHAR},
#{sex,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP},
#{status,jdbcType=INTEGER},
update tab_user
`name` = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
`status` = #{status,jdbcType=INTEGER},
where id = #{id,jdbcType=BIGINT}
update tab_user
set `name` = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
`status` = #{status,jdbcType=INTEGER}
where id = #{id,jdbcType=BIGINT}
delete from tab_user