Commit a2591f68b61f380e5866e680d1b42d1b153754a4

Authored by 潘钊
1 parent 8dd6f47c

add 批量插入工具类

src/main/java/com/bsth/vehicle/GetSchedulePlanThread.java renamed to src/main/java/com/bsth/service/realcontrol/GetSchedulePlanThread.java
1   -package com.bsth.vehicle;
  1 +package com.bsth.service.realcontrol;
2 2  
3 3 import java.text.SimpleDateFormat;
4 4 import java.util.Date;
... ... @@ -15,6 +15,7 @@ import com.bsth.entity.realcontrol.ScheduleRealInfo;
15 15 import com.bsth.entity.schedule.SchedulePlanInfo;
16 16 import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;
17 17 import com.bsth.repository.schedule.SchedulePlanInfoRepository;
  18 +import com.bsth.util.BatchSaveUtils;
18 19  
19 20 /**
20 21 *
... ... @@ -35,26 +36,35 @@ public class GetSchedulePlanThread extends Thread{
35 36 @Autowired
36 37 ScheduleRealInfoRepository scheduleRealInfoRepository;
37 38  
38   - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  39 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
  40 + ,sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
39 41  
40   - SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  42 +
  43 + SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
41 44  
42 45 @Override
43 46 public void run() {
44 47 try{
45   - List<SchedulePlanInfo> list = schedulePlanInfoRepository.findByDate(/*sdf.format(new Date())*/"2016-06-01");
46   - logger.info("开始................." + sdf2.format(new Date(System.currentTimeMillis())));
  48 + String dateStr = /*sdf.format(new Date())*/"2016-06-01";
  49 + List<SchedulePlanInfo> list = schedulePlanInfoRepository.findByDate(dateStr);
  50 + logger.info("开始................." + sdf3.format(new Date(System.currentTimeMillis())));
47 51  
48   - //写入到实际计划表
  52 + //实际排班计划
49 53 List<ScheduleRealInfo> realList = JSONArray.parseArray(JSON.toJSONString(list), ScheduleRealInfo.class);
50 54  
51 55 for(ScheduleRealInfo item : realList){
52 56 item.setDfsj(item.getFcsj());
  57 + //发车时间戳
  58 + item.setFcsjT(sdf2.parse(dateStr + " " + item.getFcsj()).getTime());
53 59 }
54 60  
55   - scheduleRealInfoRepository.save(realList);
56   - logger.info("结束................." + sdf2.format(new Date(System.currentTimeMillis())));
  61 + //scheduleRealInfoRepository.save(realList);
  62 + new BatchSaveUtils<ScheduleRealInfo>().saveListMysql(realList, ScheduleRealInfo.class);
  63 + //写入缓存
  64 + ScheduleBuffer.init(realList);
  65 + logger.info("结束................." + sdf3.format(new Date(System.currentTimeMillis())));
57 66  
  67 + logger.info("获取当天实际排班计划数量:" + realList.size());
58 68 }catch(Exception e){
59 69 logger.error("",e);
60 70 }
... ...
src/main/java/com/bsth/util/BatchSaveUtils.java 0 → 100644
  1 +package com.bsth.util;
  2 +
  3 +import java.lang.reflect.Field;
  4 +import java.sql.Connection;
  5 +import java.sql.DriverManager;
  6 +import java.sql.PreparedStatement;
  7 +import java.util.ArrayList;
  8 +import java.util.List;
  9 +
  10 +import javax.persistence.Table;
  11 +import javax.persistence.Transient;
  12 +
  13 +import org.apache.commons.lang3.CharUtils;
  14 +import org.apache.commons.lang3.StringUtils;
  15 +import org.slf4j.Logger;
  16 +import org.slf4j.LoggerFactory;
  17 +
  18 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  19 +
  20 +/**
  21 + *
  22 + * @ClassName: BatchSaveUtils
  23 + * @Description: TODO(批量持久化工具类)
  24 + * @author PanZhao
  25 + * @date 2016年6月14日 上午10:21:53
  26 + *
  27 + */
  28 +public class BatchSaveUtils<T> {
  29 +
  30 + private static String driver;
  31 + private static String url;
  32 + private static String uname;
  33 + private static String pwd;
  34 +
  35 + final static int batchSize = 5000;
  36 +
  37 + Logger logger = LoggerFactory.getLogger(this.getClass());
  38 +
  39 + static {
  40 + Tools t = new Tools("application.properties");
  41 + driver = t.getValue("spring.datasource.driver-class-name");
  42 + url = t.getValue("spring.datasource.url");
  43 + uname = t.getValue("spring.datasource.username");
  44 + pwd = t.getValue("spring.datasource.password");
  45 + }
  46 +
  47 + public int saveListMysql(List<T> list, Class<T> clazz){
  48 + //获取泛型 T 的字节码
  49 + Table table = clazz.getAnnotation(Table.class);
  50 + if(null == table){
  51 + logger.error("找不到" + clazz.getSimpleName() + "类的表映射");
  52 + return -1;
  53 + }
  54 + List<Field> fs = fieldFilter(clazz.getDeclaredFields());
  55 + String sql = createSql(table, fs);
  56 + logger.info(sql);
  57 +
  58 + //每5000条批量入库一次
  59 + try{
  60 + Connection conn = getConn();
  61 + conn.setAutoCommit(false);
  62 + PreparedStatement ps = conn.prepareStatement(sql);
  63 +
  64 + int fsize = fs.size(), count = 0;
  65 + for(T t : list){
  66 + count ++;
  67 + for(int i = 0; i < fsize; i ++){
  68 + ps.setObject(i + 1, fs.get(i).get(t));
  69 + }
  70 +
  71 + if(count % batchSize == 0){
  72 + ps.executeBatch();
  73 + ps.clearBatch();
  74 + }
  75 + }
  76 + ps.executeBatch();
  77 + }catch(Exception e){
  78 + logger.error("",e);
  79 + return -1;
  80 + }
  81 +
  82 + return 0;
  83 + }
  84 +
  85 + public String createSql(Table table, List<Field> fs){
  86 + String sqlBefore = "insert into " + table.name() + "("
  87 + ,sqlValues = "(";
  88 + for(Field field : fs){
  89 + sqlBefore += (propertyToField(field.getName()) + ",");
  90 + sqlValues += "?,";
  91 + }
  92 + sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ")";
  93 + sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ")";
  94 +
  95 + return sqlBefore + " " + sqlValues;
  96 + }
  97 +
  98 + public static void main(String[] args) {
  99 + List<ScheduleRealInfo> list = new ArrayList<>();
  100 +
  101 + new BatchSaveUtils<ScheduleRealInfo>().saveListMysql(list, ScheduleRealInfo.class);
  102 + }
  103 +
  104 + /**
  105 + *
  106 + * @Title: propertyToField
  107 + * @Description: TODO(java转数据库字段名)
  108 + * @param @param property
  109 + * @throws
  110 + */
  111 + public static String propertyToField(String property) {
  112 + if (null == property) {
  113 + return "";
  114 + }
  115 + char[] chars = property.toCharArray();
  116 + StringBuffer sb = new StringBuffer();
  117 + for (char c : chars) {
  118 + if (CharUtils.isAsciiAlphaUpper(c)) {
  119 + sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
  120 + } else {
  121 + sb.append(c);
  122 + }
  123 + }
  124 + return sb.toString();
  125 + }
  126 +
  127 + public static List<Field> fieldFilter(Field[] fields){
  128 + List<Field> fs = new ArrayList<>();
  129 + for(Field field : fields){
  130 + field.setAccessible(true);
  131 + //忽略 Transient 字段
  132 + if(field.getAnnotation(Transient.class) != null)
  133 + continue;
  134 + fs.add(field);
  135 + }
  136 + return fs;
  137 + }
  138 +
  139 + public static Connection getConn() throws Exception{
  140 + Class.forName(driver);
  141 + Connection conn = DriverManager.getConnection(url,uname,pwd);
  142 + return conn;
  143 + }
  144 +}
... ...