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