SampleService.java 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package com.ruoyi.job.service;
  2. import com.xxl.job.core.context.XxlJobHelper;
  3. import com.xxl.job.core.handler.annotation.XxlJob;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.stereotype.Service;
  6. import java.io.BufferedInputStream;
  7. import java.io.BufferedReader;
  8. import java.io.DataOutputStream;
  9. import java.io.InputStreamReader;
  10. import java.net.HttpURLConnection;
  11. import java.net.URL;
  12. import java.util.Arrays;
  13. import java.util.concurrent.TimeUnit;
  14. /**
  15. * XxlJob开发示例(Bean模式)
  16. * <p>
  17. * 开发步骤:
  18. * 1、任务开发:在Spring Bean实例中,开发Job方法;
  19. * 2、注解配置:为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。
  20. * 3、执行日志:需要通过 "XxlJobHelper.log" 打印执行日志;
  21. * 4、任务结果:默认任务结果为 "成功" 状态,不需要主动设置;如有诉求,比如设置任务结果为失败,可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果;
  22. *
  23. * @author xuxueli 2019-12-11 21:52:51
  24. */
  25. @Slf4j
  26. @Service
  27. public class SampleService {
  28. /**
  29. * 1、简单任务示例(Bean模式)
  30. */
  31. @XxlJob("demoJobHandler")
  32. public void demoJobHandler() throws Exception {
  33. XxlJobHelper.log("XXL-JOB, Hello World.");
  34. for (int i = 0; i < 5; i++) {
  35. XxlJobHelper.log("beat at:" + i);
  36. TimeUnit.SECONDS.sleep(2);
  37. }
  38. // default success
  39. }
  40. /**
  41. * 2、分片广播任务
  42. */
  43. @XxlJob("shardingJobHandler")
  44. public void shardingJobHandler() throws Exception {
  45. // 分片参数
  46. int shardIndex = XxlJobHelper.getShardIndex();
  47. int shardTotal = XxlJobHelper.getShardTotal();
  48. XxlJobHelper.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
  49. // 业务逻辑
  50. for (int i = 0; i < shardTotal; i++) {
  51. if (i == shardIndex) {
  52. XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
  53. } else {
  54. XxlJobHelper.log("第 {} 片, 忽略", i);
  55. }
  56. }
  57. }
  58. /**
  59. * 3、命令行任务
  60. */
  61. @XxlJob("commandJobHandler")
  62. public void commandJobHandler() throws Exception {
  63. String command = XxlJobHelper.getJobParam();
  64. int exitValue = -1;
  65. BufferedReader bufferedReader = null;
  66. try {
  67. // command process
  68. ProcessBuilder processBuilder = new ProcessBuilder();
  69. processBuilder.command(command);
  70. processBuilder.redirectErrorStream(true);
  71. Process process = processBuilder.start();
  72. //Process process = Runtime.getRuntime().exec(command);
  73. BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
  74. bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
  75. // command log
  76. String line;
  77. while ((line = bufferedReader.readLine()) != null) {
  78. XxlJobHelper.log(line);
  79. }
  80. // command exit
  81. process.waitFor();
  82. exitValue = process.exitValue();
  83. } catch (Exception e) {
  84. XxlJobHelper.log(e);
  85. } finally {
  86. if (bufferedReader != null) {
  87. bufferedReader.close();
  88. }
  89. }
  90. if (exitValue == 0) {
  91. // default success
  92. } else {
  93. XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
  94. }
  95. }
  96. /**
  97. * 4、跨平台Http任务
  98. * 参数示例:
  99. * "url: http://www.baidu.com\n" +
  100. * "method: get\n" +
  101. * "data: content\n";
  102. */
  103. @XxlJob("httpJobHandler")
  104. public void httpJobHandler() throws Exception {
  105. // param parse
  106. String param = XxlJobHelper.getJobParam();
  107. if (param == null || param.trim().length() == 0) {
  108. XxlJobHelper.log("param[" + param + "] invalid.");
  109. XxlJobHelper.handleFail();
  110. return;
  111. }
  112. String[] httpParams = param.split("\n");
  113. String url = null;
  114. String method = null;
  115. String data = null;
  116. for (String httpParam : httpParams) {
  117. if (httpParam.startsWith("url:")) {
  118. url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
  119. }
  120. if (httpParam.startsWith("method:")) {
  121. method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
  122. }
  123. if (httpParam.startsWith("data:")) {
  124. data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
  125. }
  126. }
  127. // param valid
  128. if (url == null || url.trim().length() == 0) {
  129. XxlJobHelper.log("url[" + url + "] invalid.");
  130. XxlJobHelper.handleFail();
  131. return;
  132. }
  133. if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
  134. XxlJobHelper.log("method[" + method + "] invalid.");
  135. XxlJobHelper.handleFail();
  136. return;
  137. }
  138. boolean isPostMethod = method.equals("POST");
  139. // request
  140. HttpURLConnection connection = null;
  141. BufferedReader bufferedReader = null;
  142. try {
  143. // connection
  144. URL realUrl = new URL(url);
  145. connection = (HttpURLConnection) realUrl.openConnection();
  146. // connection setting
  147. connection.setRequestMethod(method);
  148. connection.setDoOutput(isPostMethod);
  149. connection.setDoInput(true);
  150. connection.setUseCaches(false);
  151. connection.setReadTimeout(5 * 1000);
  152. connection.setConnectTimeout(3 * 1000);
  153. connection.setRequestProperty("connection", "Keep-Alive");
  154. connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
  155. connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
  156. // do connection
  157. connection.connect();
  158. // data
  159. if (isPostMethod && data != null && data.trim().length() > 0) {
  160. DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
  161. dataOutputStream.write(data.getBytes("UTF-8"));
  162. dataOutputStream.flush();
  163. dataOutputStream.close();
  164. }
  165. // valid StatusCode
  166. int statusCode = connection.getResponseCode();
  167. if (statusCode != 200) {
  168. throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
  169. }
  170. // result
  171. bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
  172. StringBuilder result = new StringBuilder();
  173. String line;
  174. while ((line = bufferedReader.readLine()) != null) {
  175. result.append(line);
  176. }
  177. String responseMsg = result.toString();
  178. XxlJobHelper.log(responseMsg);
  179. return;
  180. } catch (Exception e) {
  181. XxlJobHelper.log(e);
  182. XxlJobHelper.handleFail();
  183. return;
  184. } finally {
  185. try {
  186. if (bufferedReader != null) {
  187. bufferedReader.close();
  188. }
  189. if (connection != null) {
  190. connection.disconnect();
  191. }
  192. } catch (Exception e2) {
  193. XxlJobHelper.log(e2);
  194. }
  195. }
  196. }
  197. /**
  198. * 5、生命周期任务示例:任务初始化与销毁时,支持自定义相关逻辑;
  199. */
  200. @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
  201. public void demoJobHandler2() throws Exception {
  202. XxlJobHelper.log("XXL-JOB, Hello World.");
  203. }
  204. public void init() {
  205. log.info("init");
  206. }
  207. public void destroy() {
  208. log.info("destory");
  209. }
  210. }