Bläddra i källkod

新增自动刷新数据库

赵冬冬 3 år sedan
förälder
incheckning
718d486d4f

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

@@ -3,9 +3,11 @@ package com.xin.shardingspherejdbcdemo;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
 
 //@SpringBootApplication(exclude = {SpringBootConfiguration.class})
 @SpringBootApplication
+@EnableScheduling
 @MapperScan("com.xin.shardingspherejdbcdemo.mapper")
 public class ShardingsphereJdbcStudyApplication {
 

+ 27 - 0
src/main/java/com/xin/shardingspherejdbcdemo/config/sharding/ApplicationRunnerImpl.java

@@ -0,0 +1,27 @@
+package com.xin.shardingspherejdbcdemo.config.sharding;
+
+import com.xin.shardingspherejdbcdemo.service.impl.JdbcServiceImpl;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.stereotype.Component;
+
+/**
+ * @author lnj
+ * createTime 2018-11-07 22:37
+ **/
+@Component
+public class ApplicationRunnerImpl implements ApplicationRunner {
+    @Autowired
+    private JdbcServiceImpl jdbcService;
+    @Override
+    public void run(ApplicationArguments args) throws Exception {
+        System.out.println("通过实现ApplicationRunner接口,在spring boot项目启动后打印参数");
+        String[] sourceArgs = args.getSourceArgs();
+        for (String arg : sourceArgs) {
+            System.out.print(arg + " ");
+        }
+        jdbcService.checkDb();
+        System.out.println();
+    }
+}

+ 0 - 88
src/main/java/com/xin/shardingspherejdbcdemo/config/sharding/DBShardingAlgorithm.java

@@ -1,88 +0,0 @@
-//package com.xin.shardingspherejdbcdemo.config.sharding;
-//
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
-//
-//import java.util.Collection;
-//
-///*
-// * @author :zjq
-// * @date :2020/11/9 10:44
-// * @description: TODO       数据表分表策略 TableShardingAlgorithm
-// * @version: V1.0
-// * @slogan: 天下风云出我辈,一入代码岁月催
-// */
-//@Slf4j
-//public class DBShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
-//    @Override
-//    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
-//
-//        System.out.println("DB  PreciseShardingAlgorithm  ");
-//        // 真实节点
-//        availableTargetNames.stream().forEach((item) -> {
-//            log.info("actual node db:{}", item);
-//        });
-//
-//        log.info("logic table name:{},rout column:{}", shardingValue.getLogicTableName(), shardingValue.getColumnName());
-//
-//        //精确分片
-//        log.info("column value:{}", shardingValue.getValue());
-//
-//        long orderId = shardingValue.getValue();
-//
-//        long db_index = orderId & (2 - 1);
-//
-//        for (String each : availableTargetNames) {
-//            if (each.equals("b"+db_index)) {
-//                return each;
-//            }
-//        }
-//
-//        throw new IllegalArgumentException();
-//    }
-//}
-//package com.xin.shardingspherejdbcdemo.config.sharding;
-//
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
-//import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
-//
-//import java.util.Collection;
-//
-///*
-// * @author :zjq
-// * @date :2020/11/9 10:44
-// * @description: TODO       数据表分表策略 TableShardingAlgorithm
-// * @version: V1.0
-// * @slogan: 天下风云出我辈,一入代码岁月催
-// */
-//@Slf4j
-//public class DBShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
-//    @Override
-//    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
-//
-//        System.out.println("DB  PreciseShardingAlgorithm  ");
-//        // 真实节点
-//        availableTargetNames.stream().forEach((item) -> {
-//            log.info("actual node db:{}", item);
-//        });
-//
-//        log.info("logic table name:{},rout column:{}", shardingValue.getLogicTableName(), shardingValue.getColumnName());
-//
-//        //精确分片
-//        log.info("column value:{}", shardingValue.getValue());
-//
-//        long orderId = shardingValue.getValue();
-//
-//        long db_index = orderId & (2 - 1);
-//
-//        for (String each : availableTargetNames) {
-//            if (each.equals("b"+db_index)) {
-//                return each;
-//            }
-//        }
-//
-//        throw new IllegalArgumentException();
-//    }
-//}

+ 0 - 18
src/main/java/com/xin/shardingspherejdbcdemo/config/sharding/DynamicTablesProperties.java

@@ -1,18 +0,0 @@
-//package com.xin.shardingspherejdbcdemo.config.sharding;
-//
-//import lombok.Data;
-//import org.springframework.boot.context.properties.ConfigurationProperties;
-//
-///**
-// * 动态分表配置
-// *
-// * @author qimok
-// * @since 2020-09-07
-// */
-//@ConfigurationProperties(prefix = "spring.shardingsphere.sharding.tables")
-//@Data
-//public class DynamicTablesProperties {
-//
-//    String[] names;
-//
-//}

+ 33 - 73
src/main/java/com/xin/shardingspherejdbcdemo/config/sharding/ShardingTableRuleActualDataNodesRefreshJob.java

@@ -1,73 +1,33 @@
-//package com.xin.shardingspherejdbcdemo.config.sharding;
-//
-//import com.google.common.collect.Maps;
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.commons.compress.utils.Sets;
-//import org.apache.ibatis.javassist.Modifier;
-//import org.apache.shardingsphere.core.rule.DataNode;
-//import org.apache.shardingsphere.core.rule.TableRule;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.scheduling.annotation.Scheduled;
-//import org.springframework.stereotype.Component;
-//
-//import javax.annotation.PostConstruct;
-//import javax.annotation.Resource;
-//import javax.sql.DataSource;
-//import java.lang.reflect.Field;
-//import java.util.Collection;
-//import java.util.List;
-//import java.util.Map;
-//import java.util.Set;
-//import java.util.concurrent.atomic.AtomicInteger;
-//
-///**
-// * 基于范围分表的 ActualDataNodes 动态刷新JOB
-// *
-// * @author qimok
-// * @since 2020-09-07
-// */
-//@Slf4j
-//@Component
-//public class ShardingTableRuleActualDataNodesRefreshJob {
-//    @Resource(name = "shardingDataSource")
-//    private DataSource dataSource;
-//
-//    @Autowired
-//    private DynamicTablesProperties dynamicTables;
-//
-//    /**
-//     * 6 个小时执行一次
-//     */
-//    @PostConstruct
-//    @Scheduled(fixedRate = 1000 * 60 * 60 * 12)
-//    public void refreshActualDataNodes() throws NoSuchFieldException, IllegalAccessException {
-//
-//    }
-//
-//    /**
-//     * 动态刷新数据源
-//     */
-//    private void dynamicRefreshDatasource(String dataSourceName, TableRule tableRule, List<DataNode> newDataNodes)
-//            throws NoSuchFieldException, IllegalAccessException {
-//        Set<String> actualTables = Sets.newHashSet();
-//        Map<DataNode, Integer> dataNodeIndexMap = Maps.newHashMap();
-//        AtomicInteger index = new AtomicInteger(0);
-//        newDataNodes.forEach(dataNode -> {
-//            actualTables.add(dataNode.getTableName());
-//            if (index.intValue() == 0) {
-//                dataNodeIndexMap.put(dataNode, 0);
-//            } else {
-//                dataNodeIndexMap.put(dataNode, index.intValue());
-//            }
-//            index.incrementAndGet();
-//        });
-//        // 动态刷新:actualDataNodesField
-//        Field actualDataNodesField = TableRule.class.getDeclaredField("actualDataNodes");
-//        Field modifiersField = Field.class.getDeclaredField("modifiers");
-//        modifiersField.setAccessible(true);
-//        modifiersField.setInt(actualDataNodesField, actualDataNodesField.getModifiers() & ~Modifier.FINAL);
-//        actualDataNodesField.setAccessible(true);
-//        actualDataNodesField.set(tableRule, newDataNodes);
-//
-//    }
-//}
+package com.xin.shardingspherejdbcdemo.config.sharding;
+
+import com.xin.shardingspherejdbcdemo.service.impl.JdbcServiceImpl;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+/**
+ * 基于范围分表的 ActualDataNodes 动态刷新JOB
+ *
+ * @author qimok
+ * @since 2020-09-07
+ */
+@Slf4j
+@Component
+public class ShardingTableRuleActualDataNodesRefreshJob {
+
+
+    /**
+     * 6 个小时执行一次
+     */
+    @Autowired
+    private JdbcServiceImpl jdbcService;
+    @Scheduled(cron = "0 0 23 * * ?")
+    public void refreshActualDataNodes(){
+        log.info("开始执行自动扩容策略");
+        jdbcService.checkDb();
+        log.info("结束执行自动扩容策略");
+    }
+
+
+}

+ 2 - 91
src/main/java/com/xin/shardingspherejdbcdemo/controller/JdbcController.java

@@ -26,11 +26,11 @@ import javax.sql.DataSource;
 import java.lang.reflect.Field;
 import java.sql.*;
 import java.util.*;
+import java.util.Date;
 import java.util.concurrent.atomic.AtomicInteger;
 
 @Controller
 @RequestMapping("/jdbc")
-@Slf4j
 public class JdbcController {
 
     static {
@@ -52,103 +52,14 @@ public class JdbcController {
     }
 
 
-    @Resource(name = "shardingDataSource")
-    private DataSource dataSource;
 
-    @Autowired
-    private MyDataSourceConfig myDataSourceConfig;
 
     @GetMapping
     @ResponseBody
     public AjaxVo saveUser() throws SQLException, NoSuchFieldException, IllegalAccessException {
-
-        Map<String, MyDataSourcePropertie> dataSourceConfig = myDataSourceConfig.getDataSourceConfig();
-
-
-        try {
-            ShardingDataSource shardingDataSource = (ShardingDataSource) dataSource;
-            ShardingRule shardingRule = shardingDataSource.getRuntimeContext().getRule();
-            //tableRule = shardingRule.getTableRule(dynamicTableName);
-            List<TableRule> tableRules = (List<TableRule>) shardingRule.getTableRules();
-
-            for (TableRule tableRule : tableRules) {
-                String logicTableName = tableRule.getLogicTable();
-                Collection<String> actualDatasourceNames = tableRule.getActualDatasourceNames();
-                for (String dataSourceName : actualDatasourceNames) {
-                    MyDataSourcePropertie myDataSourcePropertie = dataSourceConfig.get(dataSourceName);
-                    if (!StringUtils.isEmpty(myDataSourcePropertie)) {
-                        //并且包含需要自动刷新的表
-                        if (myDataSourcePropertie.getTables().contains(logicTableName)) {
-                            //获取最近节点
-                            List<DataNode> newDataNodes = getDataNodes(myDataSourcePropertie, dataSourceName, logicTableName);
-                            //刷新数据库jdbc连接信息
-                            dynamicRefreshDatasource(dataSourceName, tableRule, newDataNodes);
-                        }
-                    }
-                }
-
-            }
-
-
-        } catch (ShardingConfigurationException e) {
-            log.error(String.format("逻辑表:%s 动态分表配置错误!"));
-        }
-
-
+        jdbcService.checkDb();
         return AjaxVo.success();
     }
 
-    /**
-     * 获取数据节点
-     */
-    private List<DataNode> getDataNodes(MyDataSourcePropertie myDaSoPro, String dataSourceName, String logicTableName) throws SQLException {
-        List<DataNode> newDataNodes = new ArrayList<>();
-        List<String> tables = JdbcUtils.queryTable(myDaSoPro.getIp(), myDaSoPro.getPort(), myDaSoPro.getDbname(), myDaSoPro.getUsername(), myDaSoPro.getPassword(), logicTableName);
-        for (String table : tables) {
-            DataNode dataNode = new DataNode(dataSourceName+"."+table);
-            newDataNodes.add(dataNode);
-        }
-        // 扩展点
-        return newDataNodes;
-    }
 
-    /**
-     * 动态刷新数据源
-     */
-    private void dynamicRefreshDatasource(String dataSourceName, TableRule tableRule, List<DataNode> newDataNodes)
-            throws NoSuchFieldException, IllegalAccessException {
-        Set<String> actualTables = Sets.newHashSet();
-        Map<DataNode, Integer> dataNodeIndexMap = Maps.newHashMap();
-        AtomicInteger index = new AtomicInteger(0);
-        newDataNodes.forEach(dataNode -> {
-            actualTables.add(dataNode.getTableName());
-            if (index.intValue() == 0) {
-                dataNodeIndexMap.put(dataNode, 0);
-            } else {
-                dataNodeIndexMap.put(dataNode, index.intValue());
-            }
-            index.incrementAndGet();
-        });
-        // 动态刷新:actualDataNodesField
-        Field actualDataNodesField = TableRule.class.getDeclaredField("actualDataNodes");
-        Field modifiersField = Field.class.getDeclaredField("modifiers");
-        modifiersField.setAccessible(true);
-        modifiersField.setInt(actualDataNodesField, actualDataNodesField.getModifiers() & ~Modifier.FINAL);
-        actualDataNodesField.setAccessible(true);
-        actualDataNodesField.set(tableRule, newDataNodes);
-        // 动态刷新:actualTablesField
-        Field actualTablesField = TableRule.class.getDeclaredField("actualTables");
-        actualTablesField.setAccessible(true);
-        actualTablesField.set(tableRule, actualTables);
-        // 动态刷新:dataNodeIndexMapField
-        Field dataNodeIndexMapField = TableRule.class.getDeclaredField("dataNodeIndexMap");
-        dataNodeIndexMapField.setAccessible(true);
-        dataNodeIndexMapField.set(tableRule, dataNodeIndexMap);
-        // 动态刷新:datasourceToTablesMapField
-        Map<String, Collection<String>> datasourceToTablesMap = Maps.newHashMap();
-        datasourceToTablesMap.put(dataSourceName, actualTables);
-        Field datasourceToTablesMapField = TableRule.class.getDeclaredField("datasourceToTablesMap");
-        datasourceToTablesMapField.setAccessible(true);
-        datasourceToTablesMapField.set(tableRule, datasourceToTablesMap);
-    }
 }

+ 116 - 0
src/main/java/com/xin/shardingspherejdbcdemo/service/impl/JdbcServiceImpl.java

@@ -1,11 +1,31 @@
 package com.xin.shardingspherejdbcdemo.service.impl;
 
+import com.google.common.collect.Maps;
+import com.xin.shardingspherejdbcdemo.config.sharding.MyDataSourceConfig;
+import com.xin.shardingspherejdbcdemo.config.sharding.MyDataSourcePropertie;
 import com.xin.shardingspherejdbcdemo.utils.JdbcUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.compress.utils.Sets;
+import org.apache.ibatis.javassist.Modifier;
+import org.apache.shardingsphere.core.config.ShardingConfigurationException;
+import org.apache.shardingsphere.core.rule.DataNode;
+import org.apache.shardingsphere.core.rule.ShardingRule;
+import org.apache.shardingsphere.core.rule.TableRule;
+import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
 
+import javax.annotation.Resource;
+import javax.sql.DataSource;
+import java.lang.reflect.Field;
 import java.sql.SQLException;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
 
 @Service
+@Slf4j
 public class JdbcServiceImpl {
 
     public boolean createTable() throws SQLException {
@@ -18,4 +38,100 @@ public class JdbcServiceImpl {
         return JdbcUtils.createTable(ip, port, dbName, username, password, tableName);
     }
 
+    @Resource(name = "shardingDataSource")
+    private DataSource dataSource;
+
+    @Autowired
+    private MyDataSourceConfig myDataSourceConfig;
+
+    @Transactional
+    public void checkDb() {
+        Map<String, MyDataSourcePropertie> dataSourceConfig = myDataSourceConfig.getDataSourceConfig();
+        try {
+            ShardingDataSource shardingDataSource = (ShardingDataSource) dataSource;
+            ShardingRule shardingRule = shardingDataSource.getRuntimeContext().getRule();
+            //tableRule = shardingRule.getTableRule(dynamicTableName);
+            List<TableRule> tableRules = (List<TableRule>) shardingRule.getTableRules();
+
+            for (TableRule tableRule : tableRules) {
+                String logicTableName = tableRule.getLogicTable();
+                Collection<String> actualDatasourceNames = tableRule.getActualDatasourceNames();
+                for (String dataSourceName : actualDatasourceNames) {
+                    MyDataSourcePropertie myDataSourcePropertie = dataSourceConfig.get(dataSourceName);
+                    if (!StringUtils.isEmpty(myDataSourcePropertie)) {
+                        //并且包含需要自动刷新的表
+                        if (myDataSourcePropertie.getTables().contains(logicTableName)) {
+                            //获取最近节点
+                            List<DataNode> newDataNodes = getDataNodes(myDataSourcePropertie, dataSourceName, logicTableName);
+                            //刷新数据库jdbc连接信息
+                            dynamicRefreshDatasource(dataSourceName, tableRule, newDataNodes);
+                        }
+                    }
+                }
+
+            }
+
+        } catch (ShardingConfigurationException | NoSuchFieldException | IllegalAccessException | SQLException e) {
+            log.error(String.format("逻辑表:%s 动态分表配置错误!"));
+        }
+    }
+
+    /**
+     * 获取数据节点
+     */
+    private List<DataNode> getDataNodes(MyDataSourcePropertie myDaSoPro, String dataSourceName, String logicTableName) throws SQLException {
+        List<DataNode> newDataNodes = new ArrayList<>();
+        Calendar date = Calendar.getInstance();
+        String year = String.valueOf(date.get(Calendar.YEAR));
+        String createTableName = logicTableName + year;
+        JdbcUtils.createTable(myDaSoPro.getIp(), myDaSoPro.getPort(), myDaSoPro.getDbname(), myDaSoPro.getUsername(), myDaSoPro.getPassword(), createTableName);
+        List<String> tables = JdbcUtils.queryTable(myDaSoPro.getIp(), myDaSoPro.getPort(), myDaSoPro.getDbname(), myDaSoPro.getUsername(), myDaSoPro.getPassword(), logicTableName);
+        for (String table : tables) {
+            DataNode dataNode = new DataNode(dataSourceName + "." + table);
+            newDataNodes.add(dataNode);
+        }
+        // 扩展点
+        return newDataNodes;
+    }
+
+    /**
+     * 动态刷新数据源
+     */
+    private void dynamicRefreshDatasource(String dataSourceName, TableRule tableRule, List<DataNode> newDataNodes)
+            throws NoSuchFieldException, IllegalAccessException {
+        Set<String> actualTables = Sets.newHashSet();
+        Map<DataNode, Integer> dataNodeIndexMap = Maps.newHashMap();
+        AtomicInteger index = new AtomicInteger(0);
+        newDataNodes.forEach(dataNode -> {
+            actualTables.add(dataNode.getTableName());
+            if (index.intValue() == 0) {
+                dataNodeIndexMap.put(dataNode, 0);
+            } else {
+                dataNodeIndexMap.put(dataNode, index.intValue());
+            }
+            index.incrementAndGet();
+        });
+        // 动态刷新:actualDataNodesField
+        Field actualDataNodesField = TableRule.class.getDeclaredField("actualDataNodes");
+        Field modifiersField = Field.class.getDeclaredField("modifiers");
+        modifiersField.setAccessible(true);
+        modifiersField.setInt(actualDataNodesField, actualDataNodesField.getModifiers() & ~Modifier.FINAL);
+        actualDataNodesField.setAccessible(true);
+        actualDataNodesField.set(tableRule, newDataNodes);
+        // 动态刷新:actualTablesField
+        Field actualTablesField = TableRule.class.getDeclaredField("actualTables");
+        actualTablesField.setAccessible(true);
+        actualTablesField.set(tableRule, actualTables);
+        // 动态刷新:dataNodeIndexMapField
+        Field dataNodeIndexMapField = TableRule.class.getDeclaredField("dataNodeIndexMap");
+        dataNodeIndexMapField.setAccessible(true);
+        dataNodeIndexMapField.set(tableRule, dataNodeIndexMap);
+        // 动态刷新:datasourceToTablesMapField
+        Map<String, Collection<String>> datasourceToTablesMap = Maps.newHashMap();
+        datasourceToTablesMap.put(dataSourceName, actualTables);
+        Field datasourceToTablesMapField = TableRule.class.getDeclaredField("datasourceToTablesMap");
+        datasourceToTablesMapField.setAccessible(true);
+        datasourceToTablesMapField.set(tableRule, datasourceToTablesMap);
+    }
+
 }

+ 31 - 48
src/main/java/com/xin/shardingspherejdbcdemo/utils/JdbcUtils.java

@@ -14,24 +14,7 @@ public class JdbcUtils {
         }
     }
 
-    public static List<String> queryTable(String ip, String port, String dbName, String username, String password, String tableName) throws SQLException {
-        List<String> tables = new ArrayList<>();
-        String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName;
-        Connection conn = null;
-        //2.获取与数据库的链接
-        conn = DriverManager.getConnection(url, username, password);
-        String sql = "select table_name from information_schema.tables where table_schema=? AND table_name LIKE ?";
-        //3.获取用于向数据库发送sql语句的Preperedstatement
-        PreparedStatement st = conn.prepareStatement(sql);//在此次传入,进行预编译
-        st.setString(1, dbName);
-        st.setString(2, tableName+"%");
-        ResultSet rs = st.executeQuery();
-        //循环取出
-        if (rs.next()) {
-            String id = rs.getString("table_name");//1代表数据库中表的列数,id在第一列也可以("id")!!!
-            System.out.println(id + " ");
-            tables.add(id);
-        }
+    public static void close(Connection conn, Statement st, ResultSet rs) {
         //6.关闭链接,释放资源
         if (rs != null) {
             try {
@@ -55,61 +38,61 @@ public class JdbcUtils {
                 e.printStackTrace();
             }
         }
+    }
+
+    public static List<String> queryTable(String ip, String port, String dbName, String username, String password, String tableName) throws SQLException {
+        List<String> tables = new ArrayList<>();
+        Connection conn = getConnection(ip, port, dbName, username, password);
+        String sql = "select table_name from information_schema.tables where table_schema=? AND table_name LIKE ?";
+        //3.获取用于向数据库发送sql语句的Preperedstatement
+        PreparedStatement st = conn.prepareStatement(sql);//在此次传入,进行预编译
+        st.setString(1, dbName);
+        st.setString(2, tableName + "%");
+        ResultSet rs = st.executeQuery();
+        //循环取出
+        while(rs.next()) {
+            String id = rs.getString(1);//1代表数据库中表的列数,id在第一列也可以("id")!!!
+            System.out.println(id + " ");
+            tables.add(id);
+        }
+        close(conn,st,rs);
         return tables;
 
     }
 
-    public static boolean createTable(String ip, String port, String dbName, String username, String password, String tableName) throws SQLException {
-        boolean flage = false;
+    private static Connection getConnection(String ip, String port, String dbName, String username, String password) throws SQLException {
         String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName;
         Connection conn = null;
         //2.获取与数据库的链接
         conn = DriverManager.getConnection(url, username, password);
+        return conn;
+    }
+
+    public static boolean createTable(String ip, String port, String dbName, String username, String password, String tableName) throws SQLException {
+        boolean flage = false;
+        Connection conn = getConnection(ip, port, dbName, username, password);
         String splitStr = "_";
         //3.获取用于向数据库发送sql语句的statement
         String[] s = tableName.split(splitStr);
         Integer year = Integer.valueOf(s[2]);
-        year = year - 1;
-        String oldTableName = s[0] + splitStr + s[1] + splitStr + year;
+        year = year + 1;
+        String newTableName = s[0] + splitStr + s[1] + splitStr + year;
         //4.向数据库发sql
         String sql = "select table_name from information_schema.tables where table_schema=? AND table_name=? ";
         //3.获取用于向数据库发送sql语句的Preperedstatement
         PreparedStatement st = conn.prepareStatement(sql);//在此次传入,进行预编译
         st.setString(1, dbName);
-        st.setString(2, tableName);
+        st.setString(2, newTableName);
         ResultSet rs = st.executeQuery();
         //循环取出(id)
         flage = rs.next();
         if (!flage) {
             Statement statement = conn.createStatement();
-            sql = "CREATE TABLE IF NOT EXISTS" + tableName + " LIKE " + oldTableName;
+            sql = "CREATE TABLE IF NOT EXISTS " + newTableName + " LIKE " + tableName;
             //3.获取用于向数据库发送sql语句的Preperedstatement
             flage = statement.execute(sql);
         }
-
-        //6.关闭链接,释放资源
-        if (rs != null) {
-            try {
-                rs.close();
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-            rs = null;
-        }
-        if (st != null) {
-            try {
-                st.close();
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
-        if (conn != null) {
-            try {
-                conn.close();
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
+        close(conn,st,rs);
         return flage;
 
     }

+ 3 - 5
src/main/resources/application-test.yml

@@ -11,9 +11,7 @@ mybatis:
     map-underscore-to-camel-case: true
     default-fetch-size: 500
     default-statement-timeout: 80
-dbinfo:
-  username: root
-  password: 123456
+
 
 mydbinfo:
   list:
@@ -40,8 +38,8 @@ spring:
         type: com.alibaba.druid.pool.DruidDataSource
         driver-class-name: com.mysql.cj.jdbc.Driver
         url: jdbc:mysql://192.168.29.131:3306/sharding_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true
-        username: ${dbinfo.username}
-        password: ${dbinfo.password}
+        username: root
+        password: 123456
     sharding:
       tables:
         #逻辑表名