SingleTableJob.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package com.yihu.quota.service.job;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.google.gson.Gson;
  5. import com.yihu.quota.contants.JobConstant;
  6. import com.yihu.quota.kafka.Producer;
  7. import com.yihu.quota.util.sql.DbKit;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.quartz.*;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.context.annotation.Scope;
  14. import org.springframework.jdbc.core.JdbcTemplate;
  15. import org.springframework.stereotype.Component;
  16. import org.springframework.web.context.support.SpringBeanAutowiringSupport;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. /**
  22. * 用于一个表就是一个多维数据集的情况,如组织机构表的数据采集
  23. * 数据采集表要求,不符合要求的表需要先改造后进行数据采集:
  24. * <p>
  25. * 表必须是单字段唯一键(或主键),不支持复合唯一键(或主键)
  26. * 过滤字段只支持单字段,不支持多字段过滤
  27. * 过滤字段只支持时间和数字字段,不支持其他类型字段
  28. *
  29. * @author l4qiang
  30. * @date 2018-09-18
  31. */
  32. @Component
  33. @Scope("prototype")
  34. @DisallowConcurrentExecution
  35. public class SingleTableJob implements Job {
  36. static private Logger logger = LoggerFactory.getLogger(SingleTableJob.class);
  37. /**
  38. * 数据来源库
  39. */
  40. protected String database;
  41. /**
  42. * 数据来源表
  43. */
  44. protected String table;
  45. /**
  46. * 表主键
  47. */
  48. protected String primeKey;
  49. /**
  50. * 过滤字段
  51. */
  52. protected String filterField;
  53. /**
  54. * 过滤字段类型
  55. */
  56. protected String filterFieldType;
  57. /**
  58. * 过滤数据步长
  59. */
  60. protected String size;
  61. /**
  62. * 开始时间
  63. */
  64. protected String start;
  65. /**
  66. * 结束时间
  67. */
  68. protected String end;
  69. /**
  70. * 执行动作 1 手动执行 2 周期执行
  71. */
  72. protected JobConstant.ExecType execType;
  73. /**
  74. * 查询列
  75. */
  76. protected String searchColumn;
  77. /**
  78. * 数据集id
  79. */
  80. protected String cubeId;
  81. protected String initializeType;//初始化方式 全表数据 table 列数据 cloumn
  82. @Autowired
  83. private Producer producer;
  84. @Autowired
  85. private JdbcTemplate jdbcTemplate;
  86. @Autowired
  87. private ObjectMapper objectMapper;
  88. @Override
  89. public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
  90. prepare(jobExecutionContext);
  91. if(initializeType.equals("table")){
  92. boolean cleanFlag = cleanData();
  93. if( !cleanFlag ){
  94. return;
  95. }
  96. }
  97. String sql = sqlGenerate();
  98. String[] countSql = sql.split("from");
  99. sql = "select count(*) from " + countSql[1];
  100. try {
  101. int rows = jdbcTemplate.queryForObject(sql, Integer.class);
  102. int perCount = 10000;
  103. if (rows > perCount) {
  104. int count = rows / perCount;
  105. int remainder = rows % perCount;
  106. if (remainder != 0) {
  107. count++;
  108. } else {
  109. remainder = perCount;
  110. }
  111. for (int i = 0; i < count; i++) {
  112. int row,start = 0;
  113. if (i != 0) {
  114. start = i * perCount;
  115. }
  116. // 确定抽取多少条数据
  117. if (i + 1 == count) {
  118. row = remainder;
  119. } else {
  120. row = perCount;
  121. }
  122. List<Map<String, Object>> list = fetch(start, row);
  123. saveData(list);
  124. }
  125. } else {
  126. List<Map<String, Object>> list = fetch(0, perCount);
  127. saveData(list);
  128. }
  129. } catch (Exception e) {
  130. e.printStackTrace();
  131. }
  132. }
  133. private void prepare(JobExecutionContext jobExecutionContext) {
  134. //spring注入
  135. SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
  136. JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
  137. initializeType = jobDataMap.getString("initializeType");
  138. database = jobDataMap.getString("database");
  139. table = jobDataMap.getString("table");
  140. primeKey = jobDataMap.getString("primeKey");
  141. filterField = jobDataMap.getString("filterField");
  142. filterFieldType = jobDataMap.getString("filterFieldType");
  143. size = jobDataMap.getString("size");
  144. start = jobDataMap.getString("start");
  145. end = jobDataMap.getString("end");
  146. if(jobDataMap.get("execType") != null){
  147. execType = JobConstant.ExecType.fromInt(jobDataMap.getIntValue("execType"));
  148. }else {
  149. execType = JobConstant.ExecType.Full;
  150. }
  151. searchColumn = jobDataMap.getString("searchColumn");
  152. cubeId = jobDataMap.getString("cubeId");
  153. }
  154. /**
  155. * 清空数据 发送消息
  156. */
  157. private boolean cleanData() {
  158. if (JobConstant.ExecType.Full.equals(execType)) {
  159. Map<String, Object> dataMap = new HashMap<>(2);
  160. dataMap.put("dataSource", "mysql");
  161. dataMap.put("database", database);
  162. dataMap.put("table", table);
  163. dataMap.put("action", "DelAll");
  164. dataMap.put("cubeId", cubeId);
  165. try {
  166. String jsonData = objectMapper.writeValueAsString(dataMap);
  167. logger.info("清除消息:{}",jsonData);
  168. return producer.sendMessage(Producer.sepTopic, jsonData);
  169. } catch (JsonProcessingException e) {
  170. e.printStackTrace();
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. private void saveData(List<Map<String, Object>> list) {
  177. if (list == null) {
  178. logger.warn("未获取到数据");
  179. return;
  180. }
  181. Map<String, Object> dataMap = new HashMap<>();
  182. dataMap.put("database", database);
  183. dataMap.put("dataSource", "mysql");
  184. dataMap.put("action", "PutAll");
  185. dataMap.put("table", table);
  186. dataMap.put("cubeId", cubeId);
  187. List<Map<String,Object>> dataList = new ArrayList<>();
  188. int p = 1;
  189. int perCount = 200;
  190. int d = list.size()/perCount;
  191. int y = list.size()%perCount;
  192. for(int i = 0; i < list.size() ; i++){
  193. Map<String,Object> map = new HashMap<>();
  194. Map<String,Object> item = list.get(i);
  195. item.forEach((key, value) -> {
  196. if (key.equals(primeKey)) {
  197. map.put("rowkey", value);
  198. }
  199. map.put(key, value);
  200. });
  201. dataList.add(map);
  202. if(list.size() < perCount){
  203. dataMap.put("dataList", dataList);
  204. sendDataMessage(dataMap);
  205. dataList.clear();
  206. }else {
  207. if((i+1) == perCount*p){
  208. p++;
  209. dataMap.put("dataList", dataList);
  210. sendDataMessage(dataMap);
  211. dataList.clear();
  212. }else{
  213. //有余数时,最后一组数据
  214. if(d > 0 && y > 0 && i==list.size()-1){
  215. dataMap.put("dataList", dataList);
  216. sendDataMessage(dataMap);
  217. dataList.clear();
  218. }
  219. }
  220. }
  221. }
  222. }
  223. private boolean sendDataMessage(Map<String,Object> dataMap){
  224. try {
  225. String jsonData = objectMapper.writeValueAsString(dataMap);
  226. Thread.sleep(50);
  227. // logger.info("消息:{}",jsonData);
  228. return producer.sendMessage(Producer.sepTopic, jsonData);
  229. } catch (JsonProcessingException e) {
  230. e.printStackTrace();
  231. } catch (InterruptedException e) {
  232. e.printStackTrace();
  233. }
  234. return false;
  235. }
  236. private List<Map<String, Object>> fetch(Integer start, Integer row) {
  237. String sql = sqlGenerate();
  238. sql += " limit " + start + "," + row;
  239. logger.info("sql={}",sql);
  240. return jdbcTemplate.queryForList(sql);
  241. }
  242. public String sqlGenerate() {
  243. StringBuilder sb = new StringBuilder();
  244. if (StringUtils.isNotEmpty(searchColumn)) {
  245. sb.append("select ").append(primeKey).append(",").append(searchColumn).append(" from ").append(database).append(".").append(table);
  246. } else {
  247. sb.append("select * from ").append(database).append(".").append(table);
  248. }
  249. if (StringUtils.isNotEmpty(filterField) && (StringUtils.isNotEmpty(start) || StringUtils.isNotEmpty(end))) {
  250. sb.append(" where ");
  251. if ("number".equals(filterFieldType)) {
  252. if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
  253. sb.append(filterField).append(">=").append(start).append(" and ").append(filterField).append("<=").append(end);
  254. } else if (StringUtils.isNotEmpty(start) && StringUtils.isEmpty(end)) {
  255. sb.append(filterField).append(">=").append(start);
  256. } else if (StringUtils.isEmpty(start) && StringUtils.isNotEmpty(end)) {
  257. sb.append(filterField).append("<=").append(end);
  258. }
  259. } else if ("date".equals(filterFieldType)) {
  260. if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
  261. sb.append(filterField).append(">=").append(DbKit.use().getLongDate(start)).append(" and ")
  262. .append(filterField).append("<=").append(DbKit.use().getLongDate(end));
  263. } else if (StringUtils.isNotEmpty(start) && StringUtils.isEmpty(end)) {
  264. sb.append(filterField).append(">=").append(DbKit.use().getLongDate(start));
  265. } else if (StringUtils.isEmpty(start) && StringUtils.isNotEmpty(end)) {
  266. sb.append(filterField).append("<=").append(DbKit.use().getLongDate(end));
  267. }
  268. } else {
  269. logger.warn("不支持的过滤字段类型");
  270. return null;
  271. }
  272. }
  273. return sb.toString();
  274. }
  275. /**
  276. * TODO:没有设置数据库来源和数据库类型,当前使用默认数据库
  277. *
  278. * @return
  279. */
  280. /*private List<Map<String, Object>> fetch() {
  281. String sql = "";
  282. if ("number".equals(filterFieldType)) {
  283. Long lngTemp = Long.parseLong(start) + Long.parseLong(size);
  284. String temp = lngTemp.toString();
  285. sql = "select * from " + table +
  286. " where " + filterField + ">=" + start + " and " + filterField + "<" + temp + " and " +
  287. filterField + "<=" + end;
  288. start = temp;
  289. } else if ("date".equals(filterFieldType)) {
  290. Date date = DateUtil.toDateFromTime(start);
  291. java.util.Calendar calendar = java.util.Calendar.getInstance();
  292. calendar.setTime(date);
  293. calendar.add(java.util.Calendar.HOUR_OF_DAY, Integer.parseInt(size));
  294. String temp = DateUtil.toString(calendar.getTime(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
  295. sql = "select * from " + table +
  296. " where " + filterField + ">=" + DbKit.use().getLongDate(start) + " and " + filterField + "<" + DbKit.use().getLongDate(temp) + " and " +
  297. filterField + "<=" + DbKit.use().getLongDate(end);
  298. start = temp;
  299. } else {
  300. logger.warn("不支持的过滤字段类型");
  301. return null;
  302. }
  303. return jdbcTemplate.queryForList(sql);
  304. }*/
  305. }