瀏覽代碼

第一次提交

赵冬冬 4 年之前
當前提交
dc6f25851f

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+.idea
+/target
+/*.iml
+/log

+ 1 - 0
README.md

@@ -0,0 +1 @@
+# springboot-shardingsphere-jdbc

+ 95 - 0
pom.xml

@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.1.7.RELEASE</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.xin</groupId>
+    <artifactId>shardingsphere-jdbc-study</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>shardingsphere-jdbc-study</name>
+    <description>Demo project for Spring Boot</description>
+
+    <properties>
+        <java.version>1.8</java.version>
+        <shardingsphere.version>4.0.0</shardingsphere.version>
+        <shardingsphere.spi.impl.version>4.0.0</shardingsphere.spi.impl.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.mybatis.spring.boot</groupId>
+            <artifactId>mybatis-spring-boot-starter</artifactId>
+            <version>2.1.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid</artifactId>
+            <version>1.1.21</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.shardingsphere</groupId>
+            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
+            <version>${shardingsphere.version}</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.41</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.junit.vintage</groupId>
+                    <artifactId>junit-vintage-engine</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <!--get set-->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+    <repositories>
+        <repository>
+            <id>aliyun-repos</id>
+            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
+            <snapshots>
+                <enabled>false</enabled>
+            </snapshots>
+        </repository>
+    </repositories>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 14 - 0
src/main/java/com/xin/shardingspherejdbcdemo/ShardingsphereJdbcStudyApplication.java

@@ -0,0 +1,14 @@
+package com.xin.shardingspherejdbcdemo;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class ShardingsphereJdbcStudyApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(ShardingsphereJdbcStudyApplication.class, args);
+    }
+
+}

+ 38 - 0
src/main/java/com/xin/shardingspherejdbcdemo/config/MyExceptionHandler.java

@@ -0,0 +1,38 @@
+package com.xin.shardingspherejdbcdemo.config;
+
+import com.xin.shardingspherejdbcdemo.entity.vo.AjaxVo;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * @author haozz
+ * @date 2018/6/19 17:16
+ * @description
+ */
+@ControllerAdvice
+@Slf4j
+public class MyExceptionHandler {
+
+    @ExceptionHandler(value = Exception.class)//指定拦截的异常
+    @ResponseBody
+    public AjaxVo errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
+        e.printStackTrace();//打印异常信息
+        log.error("发生了错误:{}", e.getMessage());
+        return AjaxVo.error(e.getMessage());
+    }
+
+    @ExceptionHandler(value = DataIntegrityViolationException.class)//指定拦截的异常
+    @ResponseBody
+    public AjaxVo dataIntegrityViolationException(HttpServletRequest request, HttpServletResponse response, DataIntegrityViolationException e) throws Exception {
+        e.printStackTrace();//打印异常信息
+        log.error("发生了错误:{}", e.getMessage());
+        String message = e.getCause().getMessage();
+        return AjaxVo.error(message);
+    }
+}

+ 31 - 0
src/main/java/com/xin/shardingspherejdbcdemo/config/task/RunJob.java

@@ -0,0 +1,31 @@
+package com.xin.shardingspherejdbcdemo.config.task;
+
+import com.xin.shardingspherejdbcdemo.mapper.UserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.stereotype.Component;
+
+@Component
+@Slf4j
+public class RunJob implements ApplicationRunner {
+
+
+    @Autowired
+    private UserMapper userMapper;
+
+    @Override
+    public void run(ApplicationArguments args) {
+        log.info("执行数据同步开始!");
+//        mongoTemplate.dropCollection(User.class);
+//        UserExample example = new UserExample();
+//        List<User> users = userMapper.selectByExample(example);
+//        if(!StringUtils.isEmpty(users)){
+//            log.info("插入数据{}", users);
+//            mongoTemplate.insertAll(users);
+//            log.info("插入数据完毕");
+//        }
+
+    }
+}

+ 4 - 0
src/main/java/com/xin/shardingspherejdbcdemo/config/task/TimeJob.java

@@ -0,0 +1,4 @@
+package com.xin.shardingspherejdbcdemo.config.task;
+
+public class TimeJob {
+}

+ 134 - 0
src/main/java/com/xin/shardingspherejdbcdemo/config/util/SnowFlake.java

@@ -0,0 +1,134 @@
+package com.xin.shardingspherejdbcdemo.config.util;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 描述: Twitter的分布式自增ID雪花算法snowflake (Java版)
+ *
+ *
+ * @author  zdd
+ * @create  2020-12-21
+ **/
+public class SnowFlake {
+
+    /**
+     * 起始的时间戳
+     */
+    private final static long START_STMP = 1480166465631L;
+
+    /**
+     * 每一部分占用的位数
+     */
+    private final static long SEQUENCE_BIT = 12; //序列号占用的位数
+    private final static long MACHINE_BIT = 5;   //机器标识占用的位数
+    private final static long DATACENTER_BIT = 5;//数据中心占用的位数
+
+    /**
+     * 每一部分的最大值
+     */
+    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
+    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
+    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
+
+    /**
+     * 每一部分向左的位移
+     */
+    private final static long MACHINE_LEFT = SEQUENCE_BIT;
+    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
+    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
+
+    private long datacenterId;  //数据中心
+    private long machineId;     //机器标识
+    private long sequence = 0L; //序列号
+    private long lastStmp = -1L;//上一次时间戳
+
+    public SnowFlake(long datacenterId, long machineId) {
+        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
+            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
+        }
+        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
+            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
+        }
+        this.datacenterId = datacenterId;
+        this.machineId = machineId;
+    }
+
+
+
+    /**
+     * 产生下一个ID
+     *
+     * @return
+     */
+    public synchronized long nextId() {
+        long currStmp = getNewstmp();
+        if (currStmp < lastStmp) {
+            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
+        }
+
+        if (currStmp == lastStmp) {
+            //相同毫秒内,序列号自增
+            sequence = (sequence + 1) & MAX_SEQUENCE;
+            //同一毫秒的序列数已经达到最大
+            if (sequence == 0L) {
+                currStmp = getNextMill();
+            }
+        } else {
+            //不同毫秒内,序列号置为0
+            sequence = 0L;
+        }
+
+        lastStmp = currStmp;
+
+        return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
+                | datacenterId << DATACENTER_LEFT       //数据中心部分
+                | machineId << MACHINE_LEFT             //机器标识部分
+                | sequence;                             //序列号部分
+    }
+
+    private long getNextMill() {
+        long mill = getNewstmp();
+        while (mill <= lastStmp) {
+            mill = getNewstmp();
+        }
+        return mill;
+    }
+
+    private long getNewstmp() {
+        return System.currentTimeMillis();
+    }
+
+    public static void main(String[] args) {
+        SnowFlake snowFlake = new SnowFlake(2, 3);
+        Map<Long, Long> map = new HashMap<>();
+        long starttime = new Date().getTime();
+        for (int i = 0; i < 100000; i++) {
+            long commonRandomCode = snowFlake.nextId();
+            Long count = map.get(commonRandomCode);
+            if (null != count) {
+                count = count + 1L;
+                map.put(commonRandomCode, count);
+            } else {
+                map.put(commonRandomCode, 1L);
+            }
+            System.err.println(commonRandomCode);
+
+        }
+
+        for (Long s : map.keySet()) {
+            Long count = map.get(s);
+            if (count > 1) {
+                System.err.println(s + "---" + count);
+            } else {
+                //System.err.println(s + "---" + count);
+            }
+        }
+        long endtime = new Date().getTime();
+        long diff = endtime - starttime;
+        long time = diff / 1000;
+        System.err.println(time + ":秒");
+
+
+    }
+}

+ 60 - 0
src/main/java/com/xin/shardingspherejdbcdemo/controller/UserController.java

@@ -0,0 +1,60 @@
+package com.xin.shardingspherejdbcdemo.controller;
+
+import com.google.common.collect.Lists;
+import com.xin.shardingspherejdbcdemo.entity.User;
+import com.xin.shardingspherejdbcdemo.service.UserService;
+import com.xin.shardingspherejdbcdemo.config.util.SnowFlake;
+import com.xin.shardingspherejdbcdemo.entity.vo.AjaxVo;
+import com.xin.shardingspherejdbcdemo.entity.vo.PageVo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+
+@RestController
+@RequestMapping("/user")
+public class UserController {
+
+    @Autowired
+    private UserService userService;
+
+    @PostMapping
+    public AjaxVo saveUser(@RequestBody User user) {
+        return AjaxVo.success(userService.save(user));
+    }
+
+    @PutMapping
+    public AjaxVo update(@RequestBody User user) {
+        return AjaxVo.success(userService.update(user));
+    }
+
+    @DeleteMapping("/{id}")
+    public AjaxVo delete(@PathVariable Long id) {
+        return AjaxVo.success(userService.delete(id));
+    }
+
+    @GetMapping("/{id}")
+    public AjaxVo info(@PathVariable Long id) {
+        return AjaxVo.success(userService.info(id));
+    }
+
+    @PostMapping("/insertlist")
+    public AjaxVo insertlist() {
+        List<User> userList = Lists.newArrayList();
+        SnowFlake snowFlake = new SnowFlake(2, 3);
+        for (int i = 0; i < 100000; i++) {
+            userList.add(new User(snowFlake.nextId(), "用户", 18 + i));
+        }
+        userService.saveList(userList);
+        return AjaxVo.success();
+    }
+
+    @GetMapping("/list")
+    public AjaxVo listUser(int pageNum, int pageSize, String name, Integer age) {
+        PageVo data = userService.list(pageNum, pageSize, name, age);
+        return AjaxVo.success(data);
+    }
+
+}
+

+ 42 - 0
src/main/java/com/xin/shardingspherejdbcdemo/entity/User.java

@@ -0,0 +1,42 @@
+package com.xin.shardingspherejdbcdemo.entity;
+
+public class User {
+    /** */
+    private Long id;
+
+    /** */
+    private String name;
+
+    /** */
+    private Integer age;
+
+    public User(Long id, String name, Integer age) {
+        this.id = id;
+        this.name = name;
+        this.age = age;
+    }
+
+    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 == null ? null : name.trim();
+    }
+
+    public Integer getAge() {
+        return age;
+    }
+
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+}

+ 390 - 0
src/main/java/com/xin/shardingspherejdbcdemo/entity/UserExample.java

@@ -0,0 +1,390 @@
+package com.xin.shardingspherejdbcdemo.entity;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class UserExample {
+    protected String orderByClause;
+
+    protected boolean distinct;
+
+    protected List<Criteria> oredCriteria;
+
+    public UserExample() {
+        oredCriteria = new ArrayList<Criteria>();
+    }
+
+    public void setOrderByClause(String orderByClause) {
+        this.orderByClause = orderByClause;
+    }
+
+    public String getOrderByClause() {
+        return orderByClause;
+    }
+
+    public void setDistinct(boolean distinct) {
+        this.distinct = distinct;
+    }
+
+    public boolean isDistinct() {
+        return distinct;
+    }
+
+    public List<Criteria> getOredCriteria() {
+        return oredCriteria;
+    }
+
+    public void or(Criteria criteria) {
+        oredCriteria.add(criteria);
+    }
+
+    public Criteria or() {
+        Criteria criteria = createCriteriaInternal();
+        oredCriteria.add(criteria);
+        return criteria;
+    }
+
+    public Criteria createCriteria() {
+        Criteria criteria = createCriteriaInternal();
+        if (oredCriteria.size() == 0) {
+            oredCriteria.add(criteria);
+        }
+        return criteria;
+    }
+
+    protected Criteria createCriteriaInternal() {
+        Criteria criteria = new Criteria();
+        return criteria;
+    }
+
+    public void clear() {
+        oredCriteria.clear();
+        orderByClause = null;
+        distinct = false;
+    }
+
+    protected abstract static class GeneratedCriteria {
+        protected List<Criterion> criteria;
+
+        protected GeneratedCriteria() {
+            super();
+            criteria = new ArrayList<Criterion>();
+        }
+
+        public boolean isValid() {
+            return criteria.size() > 0;
+        }
+
+        public List<Criterion> getAllCriteria() {
+            return criteria;
+        }
+
+        public List<Criterion> getCriteria() {
+            return criteria;
+        }
+
+        protected void addCriterion(String condition) {
+            if (condition == null) {
+                throw new RuntimeException("Value for condition cannot be null");
+            }
+            criteria.add(new Criterion(condition));
+        }
+
+        protected void addCriterion(String condition, Object value, String property) {
+            if (value == null) {
+                throw new RuntimeException("Value for " + property + " cannot be null");
+            }
+            criteria.add(new Criterion(condition, value));
+        }
+
+        protected void addCriterion(String condition, Object value1, Object value2, String property) {
+            if (value1 == null || value2 == null) {
+                throw new RuntimeException("Between values for " + property + " cannot be null");
+            }
+            criteria.add(new Criterion(condition, value1, value2));
+        }
+
+        public Criteria andIdIsNull() {
+            addCriterion("id is null");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdIsNotNull() {
+            addCriterion("id is not null");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdEqualTo(Long value) {
+            addCriterion("id =", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdNotEqualTo(Long value) {
+            addCriterion("id <>", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdGreaterThan(Long value) {
+            addCriterion("id >", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdGreaterThanOrEqualTo(Long value) {
+            addCriterion("id >=", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdLessThan(Long value) {
+            addCriterion("id <", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdLessThanOrEqualTo(Long value) {
+            addCriterion("id <=", value, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdIn(List<Long> values) {
+            addCriterion("id in", values, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdNotIn(List<Long> values) {
+            addCriterion("id not in", values, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdBetween(Long value1, Long value2) {
+            addCriterion("id between", value1, value2, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andIdNotBetween(Long value1, Long value2) {
+            addCriterion("id not between", value1, value2, "id");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameIsNull() {
+            addCriterion("name is null");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameIsNotNull() {
+            addCriterion("name is not null");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameEqualTo(String value) {
+            addCriterion("name =", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameNotEqualTo(String value) {
+            addCriterion("name <>", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameGreaterThan(String value) {
+            addCriterion("name >", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameGreaterThanOrEqualTo(String value) {
+            addCriterion("name >=", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameLessThan(String value) {
+            addCriterion("name <", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameLessThanOrEqualTo(String value) {
+            addCriterion("name <=", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameLike(String value) {
+            addCriterion("name like", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameNotLike(String value) {
+            addCriterion("name not like", value, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameIn(List<String> values) {
+            addCriterion("name in", values, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameNotIn(List<String> values) {
+            addCriterion("name not in", values, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameBetween(String value1, String value2) {
+            addCriterion("name between", value1, value2, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andNameNotBetween(String value1, String value2) {
+            addCriterion("name not between", value1, value2, "name");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeIsNull() {
+            addCriterion("age is null");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeIsNotNull() {
+            addCriterion("age is not null");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeEqualTo(Integer value) {
+            addCriterion("age =", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeNotEqualTo(Integer value) {
+            addCriterion("age <>", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeGreaterThan(Integer value) {
+            addCriterion("age >", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeGreaterThanOrEqualTo(Integer value) {
+            addCriterion("age >=", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeLessThan(Integer value) {
+            addCriterion("age <", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeLessThanOrEqualTo(Integer value) {
+            addCriterion("age <=", value, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeIn(List<Integer> values) {
+            addCriterion("age in", values, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeNotIn(List<Integer> values) {
+            addCriterion("age not in", values, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeBetween(Integer value1, Integer value2) {
+            addCriterion("age between", value1, value2, "age");
+            return (Criteria) this;
+        }
+
+        public Criteria andAgeNotBetween(Integer value1, Integer value2) {
+            addCriterion("age not between", value1, value2, "age");
+            return (Criteria) this;
+        }
+    }
+
+    public static class Criteria extends GeneratedCriteria {
+
+        protected Criteria() {
+            super();
+        }
+    }
+
+    public static class Criterion {
+        private String condition;
+
+        private Object value;
+
+        private Object secondValue;
+
+        private boolean noValue;
+
+        private boolean singleValue;
+
+        private boolean betweenValue;
+
+        private boolean listValue;
+
+        private String typeHandler;
+
+        public String getCondition() {
+            return condition;
+        }
+
+        public Object getValue() {
+            return value;
+        }
+
+        public Object getSecondValue() {
+            return secondValue;
+        }
+
+        public boolean isNoValue() {
+            return noValue;
+        }
+
+        public boolean isSingleValue() {
+            return singleValue;
+        }
+
+        public boolean isBetweenValue() {
+            return betweenValue;
+        }
+
+        public boolean isListValue() {
+            return listValue;
+        }
+
+        public String getTypeHandler() {
+            return typeHandler;
+        }
+
+        protected Criterion(String condition) {
+            super();
+            this.condition = condition;
+            this.typeHandler = null;
+            this.noValue = true;
+        }
+
+        protected Criterion(String condition, Object value, String typeHandler) {
+            super();
+            this.condition = condition;
+            this.value = value;
+            this.typeHandler = typeHandler;
+            if (value instanceof List<?>) {
+                this.listValue = true;
+            } else {
+                this.singleValue = true;
+            }
+        }
+
+        protected Criterion(String condition, Object value) {
+            this(condition, value, null);
+        }
+
+        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
+            super();
+            this.condition = condition;
+            this.value = value;
+            this.secondValue = secondValue;
+            this.typeHandler = typeHandler;
+            this.betweenValue = true;
+        }
+
+        protected Criterion(String condition, Object value, Object secondValue) {
+            this(condition, value, secondValue, null);
+        }
+    }
+}

+ 71 - 0
src/main/java/com/xin/shardingspherejdbcdemo/entity/vo/AjaxVo.java

@@ -0,0 +1,71 @@
+package com.xin.shardingspherejdbcdemo.entity.vo;
+
+public class AjaxVo<T> {
+    static interface Code {
+        static int SUCCESS = 0;
+        static int ERROR = 1;
+    }
+
+    static interface MSG {
+        static String SUCCESS = "成功!";
+        static String ERROR = "系统错误!";
+    }
+
+
+    private int code;
+    private String msg;
+    private T data;
+
+    public static <T> AjaxVo success() {
+        AjaxVo ajaxVo = new AjaxVo();
+        ajaxVo.setMsg(MSG.SUCCESS);
+        ajaxVo.setCode(Code.SUCCESS);
+        return ajaxVo;
+    }
+
+    public static <T> AjaxVo success(T t) {
+        AjaxVo ajaxVo = new AjaxVo();
+        ajaxVo.setData(t);
+        ajaxVo.setMsg(MSG.SUCCESS);
+        ajaxVo.setCode(Code.SUCCESS);
+        return ajaxVo;
+    }
+
+    public static AjaxVo error(String msg) {
+        AjaxVo ajaxVo = new AjaxVo();
+        ajaxVo.setMsg(msg);
+        ajaxVo.setCode(Code.ERROR);
+        return ajaxVo;
+    }
+
+    public static AjaxVo error() {
+        AjaxVo ajaxVo = new AjaxVo();
+        ajaxVo.setMsg(MSG.ERROR);
+        ajaxVo.setCode(Code.ERROR);
+        return ajaxVo;
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public void setCode(int code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public T getData() {
+        return data;
+    }
+
+    public void setData(T data) {
+        this.data = data;
+    }
+}

+ 17 - 0
src/main/java/com/xin/shardingspherejdbcdemo/entity/vo/PageVo.java

@@ -0,0 +1,17 @@
+package com.xin.shardingspherejdbcdemo.entity.vo;
+
+import lombok.Data;
+
+@Data
+public class PageVo<T> {
+    long total;
+    T data;
+
+    public static <T> PageVo data(T t, long total) {
+
+        PageVo pageVo = new PageVo<>();
+        pageVo.setData(t);
+        pageVo.setTotal(total);
+        return pageVo;
+    }
+}

+ 44 - 0
src/main/java/com/xin/shardingspherejdbcdemo/mapper/UserMapper.java

@@ -0,0 +1,44 @@
+package com.xin.shardingspherejdbcdemo.mapper;
+
+import com.xin.shardingspherejdbcdemo.entity.User;
+import com.xin.shardingspherejdbcdemo.entity.UserExample;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+@Mapper
+public interface UserMapper {
+
+    int countByExample(UserExample example);
+
+    int deleteByExample(UserExample example);
+
+    int deleteByPrimaryKey(Long id);
+
+    int insert(User record);
+
+    int insertSelective(User record);
+
+    List<User> selectByExample(UserExample example);
+
+    User selectByPrimaryKey(Long id);
+
+    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
+
+    int updateByExample(@Param("record") User record, @Param("example") UserExample example);
+
+    int updateByPrimaryKeySelective(User record);
+
+    int updateByPrimaryKey(User record);
+
+
+
+
+
+
+    List<User> selectAll(List<Long> list);
+
+
+    void insertAll(List<User> list);
+}

+ 32 - 0
src/main/java/com/xin/shardingspherejdbcdemo/service/UserService.java

@@ -0,0 +1,32 @@
+package com.xin.shardingspherejdbcdemo.service;
+
+
+import com.xin.shardingspherejdbcdemo.entity.User;
+import com.xin.shardingspherejdbcdemo.entity.vo.PageVo;
+
+import java.util.List;
+
+
+public interface UserService {
+
+    /**
+     * 获取所有用户信息
+     */
+    PageVo list(int pageNum, int pageSize, String name, Integer age);
+
+
+    /**
+     * 单个 保存用户信息
+     *
+     * @param user
+     */
+    User save(User user);
+
+    String saveList(List<User> list);
+
+    User info(Long id);
+
+    User update(User user);
+
+    Long delete(Long id);
+}

+ 104 - 0
src/main/java/com/xin/shardingspherejdbcdemo/service/impl/UserServiceImpl.java

@@ -0,0 +1,104 @@
+package com.xin.shardingspherejdbcdemo.service.impl;
+
+
+import com.xin.shardingspherejdbcdemo.config.util.SnowFlake;
+import com.xin.shardingspherejdbcdemo.entity.User;
+import com.xin.shardingspherejdbcdemo.entity.UserExample;
+import com.xin.shardingspherejdbcdemo.entity.vo.PageVo;
+import com.xin.shardingspherejdbcdemo.mapper.UserMapper;
+import com.xin.shardingspherejdbcdemo.service.UserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
+
+
+@Service
+public class UserServiceImpl implements UserService {
+
+    @Autowired
+    private UserMapper userMapper;
+
+    @Override
+    public PageVo list(int pageNum, int pageSize, String name, Integer age) {
+
+        return null;
+    }
+
+    private void getUser(List<User> users, List<Long> list) {
+        int listCount = list.size();
+        int pageSize = 1000;//一页数量
+        int pageNumer = listCount % pageSize == 0 ? listCount / pageSize : listCount / pageSize + 1;
+        for (int i = 0; i < pageNumer; i++) {
+            int start = i * pageSize;
+            int end = start + pageSize;
+            //防止索引越界
+            if (i == (pageNumer - 1)) {
+                end = list.size();
+            }
+            //实现分页
+            List<Long> ids = list.subList(start, end);
+            users.addAll(userMapper.selectAll(ids));
+            //写业务逻辑传参pageList参数
+            System.out.println("分页list长度:" + ids.size());
+        }
+    }
+
+
+    @Override
+    @Transactional
+    public User save(User user) {
+        SnowFlake snowFlake = new SnowFlake(2, 3);
+        user.setId(snowFlake.nextId());
+        userMapper.insert(user);
+        return user;
+    }
+
+    @Override
+    @Transactional
+    public String saveList(List<User> list) {
+
+        int listCount = list.size();
+        int pageSize = 10000;//一页数量
+        int pageNumer = listCount % pageSize == 0 ? listCount / pageSize : listCount / pageSize + 1;
+        for (int i = 0; i < pageNumer; i++) {
+            int start = i * pageSize;
+            int end = start + pageSize;
+            //防止索引越界
+            if (i == (pageNumer - 1)) {
+                end = list.size();
+            }
+            //实现分页
+            List<User> users = list.subList(start, end);
+            userMapper.insertAll(users);
+            //写业务逻辑传参pageList参数
+            System.out.println("分页list长度:" + users.size());
+        }
+        return "保存成功";
+    }
+
+    @Override
+    public User info(Long id) {
+        return userMapper.selectByPrimaryKey(id);
+    }
+
+    @Override
+    @Transactional
+    public User update(User user) {
+        User userRe = userMapper.selectByPrimaryKey(user.getId());
+        UserExample example = new UserExample();
+        example.createCriteria().andIdEqualTo(userRe.getId()).andAgeEqualTo(userRe.getAge());
+        int i = userMapper.updateByExampleSelective(user, example);
+        return user;
+    }
+
+    @Override
+    @Transactional
+    public Long delete(Long id) {
+        userMapper.deleteByPrimaryKey(id);
+        return id;
+    }
+
+
+}

+ 13 - 0
src/main/resources/application.yml

@@ -0,0 +1,13 @@
+server:
+  port: 8087
+spring:
+  shardingsphere:
+    datasource:
+      names: master0
+      # Êý¾ÝÔ´ Ö÷¿â
+      master0:
+        type: com.alibaba.druid.pool.DruidDataSource
+        driver-class-name: com.mysql.cj.jdbc.Driver
+        url: jdbc:mysql://192.168.29.131:3306/study?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
+        username: root
+        password: 123456

+ 77 - 0
src/main/resources/application.yml.cp

@@ -0,0 +1,77 @@
+server:
+  port: 8086
+mybatis:
+  mapper-locations: classpath*:mapper/*.xml
+#指定mybatis信息
+# 数据源 主库、从库 -- 读写分离
+#spring.shardingsphere.datasource.names=master,slave0
+# 数据源 主库 --仅分表不分库
+#spring.shardingsphere.datasource.names=master
+# 数据源 主库db0、主库db1 -- 分库分表
+spring:
+  shardingsphere:
+    datasource:
+      names: master0,master1
+      # 数据源 主库
+      master0:
+        type: com.alibaba.druid.pool.DruidDataSource
+        driver-class-name: com.mysql.cj.jdbc.Driver
+        url: jdbc:mysql://182.61.59.216:3306/db0?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
+        username: root
+        password: 123456
+      # 数据源 主库
+      master1:
+        type: com.alibaba.druid.pool.DruidDataSource
+        driver-class-name: com.mysql.cj.jdbc.Driver
+        url: jdbc:mysql://182.61.59.216:3306/db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
+        username: root
+        password: 123456
+      ## 数据源 从库
+#      slave0:
+#        type: com.alibaba.druid.pool.DruidDataSource
+#        driver-class-name: com.mysql.cj.jdbc.Driver
+#        url: jdbc:mysql://182.61.59.216:3306/db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
+#        username: root
+#        password: 123456
+
+    ## 读写分离
+    ##spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
+    #spring.shardingsphere.masterslave.name=ms
+    #spring.shardingsphere.masterslave.master-data-source-name=master
+    #spring.shardingsphere.masterslave.slave-data-source-names=slave0
+
+    ## 分库
+    #根据ID分库
+    #spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=id
+    #spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=master$->{id % 2}
+
+    #根据年龄分库
+    sharding:
+      default-database-strategy:
+        inline:
+          sharding-column: age
+          algorithm-expression: master$->{age > 30?0:1}
+        #数据分表规则--仅分表不分库
+        #注意:tables.user中的user是逻辑表
+        #仅分表时使用,单一写表,指定所需分的表,分user1、user2
+        #spring.shardingsphere.sharding.tables.user.actual-data-nodes=master.user$->{0..1}
+        #同时分库分表时使用
+        tables.user:
+          actual-data-nodes: master$->{0..1}.user$->{0..1}
+          ##行表达式分片策略
+          user:
+            table-strategy:
+              inline:
+                sharding-column: id
+                #分表两个,所以规则为主键除以2取模
+                algorithm-expression: user$->{id % 2}
+
+  ##用于单分片键的标准分片场景
+  ##指定自增主键
+  #spring.shardingsphere.sharding.tables.user.key-generator.column= id
+  ##自增列值生成器类型,缺省表示使用默认自增列值生成器。可使用用户自定义的列值生成器或选择内置类型:SNOWFLAKE/UUID
+  #spring.shardingsphere.sharding.tables.user.key-generator.type= SNOWFLAKE
+  #打印sql
+  props:
+    sql:
+      show: true

+ 38 - 0
src/main/resources/db1.sql

@@ -0,0 +1,38 @@
+/*
+Navicat MySQL Data Transfer
+
+Source Server         : 自己的百度云mysql
+Source Server Version : 50732
+Source Host           : 182.61.59.216:3306
+Source Database       : db1
+
+Target Server Type    : MYSQL
+Target Server Version : 50732
+File Encoding         : 65001
+
+Date: 2020-12-31 15:35:47
+*/
+
+SET FOREIGN_KEY_CHECKS=0;
+
+-- ----------------------------
+-- Table structure for user0
+-- ----------------------------
+DROP TABLE IF EXISTS `user0`;
+CREATE TABLE `user0` (
+  `id` bigint(18) NOT NULL AUTO_INCREMENT,
+  `name` varchar(10) DEFAULT NULL,
+  `age` int(11) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=126 DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for user1
+-- ----------------------------
+DROP TABLE IF EXISTS `user1`;
+CREATE TABLE `user1` (
+  `id` bigint(11) NOT NULL AUTO_INCREMENT,
+  `name` varchar(10) DEFAULT NULL,
+  `age` int(11) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=1018 DEFAULT CHARSET=utf8mb4;

+ 55 - 0
src/main/resources/logback-spring.xml

@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration scan="true" scanPeriod="60 seconds" debug="false">
+    <contextName>febs</contextName>
+    <springProperty scope="context" name="springAppName" source="spring.application.name"/>
+    <property name="log.path" value="log/shardingsphere-jdbc-demo-all" />
+    <property name="log.maxHistory" value="15" />
+    <property name="log.colorPattern" value="%magenta(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %boldCyan([${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]) %yellow(%thread) %green(%logger) %msg%n"/>
+    <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level [${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}] %thread %logger %msg%n"/>
+
+    <!--输出到控制台-->
+    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
+        <encoder>
+            <pattern>${log.colorPattern}</pattern>
+        </encoder>
+    </appender>
+
+    <!--输出到文件-->
+    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <fileNamePattern>${log.path}/info/info.%d{yyyy-MM-dd}.log</fileNamePattern>
+            <MaxHistory>${log.maxHistory}</MaxHistory>
+        </rollingPolicy>
+        <encoder>
+            <pattern>${log.pattern}</pattern>
+        </encoder>
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>INFO</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <fileNamePattern>${log.path}/error/error.%d{yyyy-MM-dd}.log</fileNamePattern>
+        </rollingPolicy>
+        <encoder>
+            <pattern>${log.pattern}</pattern>
+        </encoder>
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>ERROR</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+    <root level="debug">
+        <appender-ref ref="console" />
+    </root>
+
+    <root level="info">
+        <appender-ref ref="file_info" />
+        <appender-ref ref="file_error" />
+    </root>
+</configuration>

+ 210 - 0
src/main/resources/mapper/UserMapper.xml

@@ -0,0 +1,210 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
+<mapper namespace="com.xin.shardingspherejdbcdemo.mapper.UserMapper" >
+    <resultMap id="BaseResultMap" type="com.xin.shardingspherejdbcdemo.entity.User" >
+        <id column="id" property="id" jdbcType="BIGINT" />
+        <result column="name" property="name" jdbcType="VARCHAR" />
+        <result column="age" property="age" jdbcType="INTEGER" />
+    </resultMap>
+    <sql id="Example_Where_Clause" >
+        <where >
+            <foreach collection="oredCriteria" item="criteria" separator="or" >
+                <if test="criteria.valid" >
+                    <trim prefix="(" suffix=")" prefixOverrides="and" >
+                        <foreach collection="criteria.criteria" item="criterion" >
+                            <choose >
+                                <when test="criterion.noValue" >
+                                    and ${criterion.condition}
+                                </when>
+                                <when test="criterion.singleValue" >
+                                    and ${criterion.condition} #{criterion.value}
+                                </when>
+                                <when test="criterion.betweenValue" >
+                                    and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
+                                </when>
+                                <when test="criterion.listValue" >
+                                    and ${criterion.condition}
+                                    <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
+                                        #{listItem}
+                                    </foreach>
+                                </when>
+                            </choose>
+                        </foreach>
+                    </trim>
+                </if>
+            </foreach>
+        </where>
+    </sql>
+    <sql id="Update_By_Example_Where_Clause" >
+        <where >
+            <foreach collection="example.oredCriteria" item="criteria" separator="or" >
+                <if test="criteria.valid" >
+                    <trim prefix="(" suffix=")" prefixOverrides="and" >
+                        <foreach collection="criteria.criteria" item="criterion" >
+                            <choose >
+                                <when test="criterion.noValue" >
+                                    and ${criterion.condition}
+                                </when>
+                                <when test="criterion.singleValue" >
+                                    and ${criterion.condition} #{criterion.value}
+                                </when>
+                                <when test="criterion.betweenValue" >
+                                    and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
+                                </when>
+                                <when test="criterion.listValue" >
+                                    and ${criterion.condition}
+                                    <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
+                                        #{listItem}
+                                    </foreach>
+                                </when>
+                            </choose>
+                        </foreach>
+                    </trim>
+                </if>
+            </foreach>
+        </where>
+    </sql>
+    <sql id="Base_Column_List" >
+    id, name, age
+  </sql>
+    <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.xin.shardingspherejdbcdemo.entity.UserExample" >
+        select
+        <if test="distinct" >
+            distinct
+        </if>
+        <include refid="Base_Column_List" />
+        from user0
+        <if test="_parameter != null" >
+            <include refid="Example_Where_Clause" />
+        </if>
+        <if test="orderByClause != null" >
+            order by ${orderByClause}
+        </if>
+    </select>
+    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
+        select
+        <include refid="Base_Column_List" />
+        from user
+        where id = #{id,jdbcType=BIGINT}
+    </select>
+    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
+    delete from user
+    where id = #{id,jdbcType=BIGINT}
+  </delete>
+    <delete id="deleteByExample" parameterType="com.xin.shardingspherejdbcdemo.entity.UserExample" >
+        delete from user
+        <if test="_parameter != null" >
+            <include refid="Example_Where_Clause" />
+        </if>
+    </delete>
+    <insert id="insert" parameterType="com.xin.shardingspherejdbcdemo.entity.User" >
+    insert into user (id, name, age)
+    values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
+  </insert>
+    <insert id="insertSelective" parameterType="com.xin.shardingspherejdbcdemo.entity.User" >
+        insert into user
+        <trim prefix="(" suffix=")" suffixOverrides="," >
+            <if test="id != null" >
+                id,
+            </if>
+            <if test="name != null" >
+                name,
+            </if>
+            <if test="age != null" >
+                age,
+            </if>
+        </trim>
+        <trim prefix="values (" suffix=")" suffixOverrides="," >
+            <if test="id != null" >
+                #{id,jdbcType=BIGINT},
+            </if>
+            <if test="name != null" >
+                #{name,jdbcType=VARCHAR},
+            </if>
+            <if test="age != null" >
+                #{age,jdbcType=INTEGER},
+            </if>
+        </trim>
+    </insert>
+    <select id="countByExample" parameterType="com.xin.shardingspherejdbcdemo.entity.UserExample" resultType="java.lang.Integer" >
+        select count(*) from user
+        <if test="_parameter != null" >
+            <include refid="Example_Where_Clause" />
+        </if>
+    </select>
+    <update id="updateByExampleSelective" parameterType="map" >
+        update user
+        <set >
+            <if test="record.id != null" >
+                id = #{record.id,jdbcType=BIGINT},
+            </if>
+            <if test="record.name != null" >
+                name = #{record.name,jdbcType=VARCHAR},
+            </if>
+            <if test="record.age != null" >
+                age = #{record.age,jdbcType=INTEGER},
+            </if>
+        </set>
+        <if test="_parameter != null" >
+            <include refid="Update_By_Example_Where_Clause" />
+        </if>
+    </update>
+    <update id="updateByExample" parameterType="map" >
+        update user
+        set id = #{record.id,jdbcType=BIGINT},
+        name = #{record.name,jdbcType=VARCHAR},
+        age = #{record.age,jdbcType=INTEGER}
+        <if test="_parameter != null" >
+            <include refid="Update_By_Example_Where_Clause" />
+        </if>
+    </update>
+    <update id="updateByPrimaryKeySelective" parameterType="com.xin.shardingspherejdbcdemo.entity.User" >
+        update user
+        <set >
+            <if test="name != null" >
+                name = #{name,jdbcType=VARCHAR},
+            </if>
+            <if test="age != null" >
+                age = #{age,jdbcType=INTEGER},
+            </if>
+        </set>
+        where id = #{id,jdbcType=BIGINT}
+    </update>
+    <update id="updateByPrimaryKey" parameterType="com.xin.shardingspherejdbcdemo.entity.User" >
+    update user
+    set name = #{name,jdbcType=VARCHAR},
+      age = #{age,jdbcType=INTEGER}
+    where id = #{id,jdbcType=BIGINT}
+  </update>
+
+    <sql id="selectAll_Base_Column_List">
+        select
+        `id`, `name`, `age`
+        from user
+    </sql>
+
+    <select id="selectAll" resultMap="BaseResultMap">
+        <include refid="selectAll_Base_Column_List"/>
+        where id in
+        <foreach collection="list" item="id" open="(" close=")" separator=",">
+            #{id}
+        </foreach>
+    </select>
+    <insert id="insertAll">
+        insert into user
+        <trim prefix="(" suffix=")" suffixOverrides=",">
+            id,
+            name,
+            age,
+        </trim>
+        values
+        <foreach collection="list" item="item" separator=",">
+            (
+            #{item.id,jdbcType=BIGINT},
+            #{item.name,jdbcType=VARCHAR},
+            #{item.age,jdbcType=INTEGER}
+            )
+        </foreach>
+
+    </insert>
+</mapper>