(1).分布式任务调度平台XXL-JOB
https://gitee.com/xuxueli0323/xxl-job
源码结构:
xxl-job-admin:调度中心
xxl-job-core:公共依赖
xxl-job-executor-samples:执行器Sample示例(选择合适的版本执行器,可直接使用,也可以参考其并将现有项目改造成执行器)
:xxl-job-executor-sample-springboot:Springboot版本,通过Springboot管理执行器,推荐这种方式;
:xxl-job-executor-sample-frameless:无框架版本;
环境:
Maven3+
Jdk1.8+
Mysql5.7+
1.clone源码,切换到稳定分支版本如2.3.0
执行SQL初始化数据库:/xxl-job/doc/db/tables_xxl_job.sql
2.调度中心
修改调度中心配置文件:
/xxl-job/xxl-job-admin/src/main/resources/application.properties
打包部署:java -jar xxx.jar
调度中心访问地址:http://localhost:8080/xxl-job-admin
默认登录账号 “admin/123456”
3.配置部署“执行器项目”
参考:xxl-job-executor-sample-springboot
坑:集成了xxl-job的项目的配置文件中appname要与xxl-job调度中心中创建的执行器的appname一致才会自动注册
(2)获取天气
心知天气:https://www.seniverse.com/
获取24小时天气(属于付费功能,测试有使用期限):见心知天气文档
/**
* 1、简单任务示例(Bean模式)
*/
@XxlJob("demoJobHandler")
public void demoJobHandler() throws Exception {
String apiUrl = "https://api.seniverse.com/v3/weather/hourly.json?key=Sh1W6lkmjYY23qPkE&location=hangzhou&language=zh-Hans&unit=c&start=0&hours=24";
Object results = JSONObject.parseObject(HttpClientUtils.sendGet(apiUrl)).get("results");
JSONObject objects = JSONObject.parseArray(results.toString()).getJSONObject(0);
JSONArray hourly = JSONObject.parseArray(objects.get("hourly").toString());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hourly.size(); i++) {
Object time = JSONObject.parseObject(hourly.get(i).toString()).get("time");
Object text = JSONObject.parseObject(hourly.get(i).toString()).get("text");
Object temperature = JSONObject.parseObject(hourly.get(i).toString()).get("temperature");
time = time.toString().split("T")[1].split("\\+")[0].substring(0, 5);
if (Objects.nonNull(text)) {
if (text.toString().contains("雨") || text.toString().contains("阴")) {
sb.append(time + " " + text + " " + temperature + "℃" + "\n\n");
}
}
}
if (!StringUtils.isBlank(sb.toString())) {
dingDingUtils.sendDingDingMsg("天气情况:", sb.toString());
}
}
(3)工具类
1.钉钉消息工具类
package com.xxl.job.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class DingDingUtils {
@Value("${dingding.team.webhoook.url}")
private String dingDingWebHookUrl;
/**
* 发送钉钉消息
*/
public void sendDingDingMsg(String title, String content) {
JSONObject data = new JSONObject();
data.put("msgtype", "markdown");
JSONObject markDownContent = new JSONObject();
markDownContent.put("title", title);
markDownContent.put("text", "### " + title + "\n #### 描述:<font color='#DC143C'>" + content + "</font>");
data.put("markdown", markDownContent);
try {
HttpClientUtils.sendPost(dingDingWebHookUrl, data);
} catch (Exception e) {
log.error("发送钉钉消息异常", e);
}
}
}
2.http工具类
package com.xxl.job.util;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtils {
private static final String ENCODING = "UTF-8";
private static final Logger log= LoggerFactory.getLogger("business_log");
public HttpClientUtils() {
}
public static String sendPost(String url, Map<String, String> headers, JSONObject data, String encoding) {
return sendPost(url, headers, JSON.toJSONString(data), encoding);
}
public static String sendPost(String url, Map<String, String> headers, String data, String encoding) {
String resultJson = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost();
try {
httpPost.setURI(new URI(url));
int i;
if (headers != null) {
Header[] allHeader = new BasicHeader[headers.size()];
i = 0;
for (Iterator var9 = headers.entrySet().iterator(); var9.hasNext(); ++i) {
Entry<String, String> entry = (Entry)var9.next();
allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
}
httpPost.setHeaders(allHeader);
}
httpPost.setEntity(new StringEntity(data, Charset.forName(encoding)));
CloseableHttpResponse response = client.execute(httpPost);
i = response.getStatusLine().getStatusCode();
if (i == 200) {
resultJson = EntityUtils.toString(response.getEntity(), encoding);
} else {
log.error("响应失败,状态码:" + i);
}
} catch (Exception var14) {
log.error("发送post请求失败", var14);
} finally {
httpPost.releaseConnection();
}
return resultJson;
}
public static String sendPost(String url, JSONObject data) {
Map<String, String> headers = new HashMap();
headers.put("content-type", "application/json; charset=utf-8");
return sendPost(url, headers, data, ENCODING);
}
public static String sendPost(String url, String data) {
Map<String, String> headers = new HashMap();
headers.put("content-type", "application/json; charset=utf-8");
return sendPost(url, headers, data, ENCODING);
}
public static String sendPost(String url, Map<String, Object> params) {
Map<String, String> headers = new HashMap();
headers.put("content-type", "application/json; charset=utf-8");
JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
return sendPost(url, headers, data, ENCODING);
}
public static String sendPost(String url, Map<String, String> headers, JSONObject data) {
return sendPost(url, headers, data, "UTF-8");
}
public static String sendPost(String url, Map<String, String> headers, Map<String, String> params) {
JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
return sendPost(url, headers, data, ENCODING);
}
public static String sendGet(String url, Map<String, Object> params, String encoding) {
String resultJson = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet();
try {
URIBuilder builder = new URIBuilder(url);
if (params != null) {
Iterator var7 = params.keySet().iterator();
while (var7.hasNext()) {
String key = (String)var7.next();
builder.addParameter(key, params.get(key).toString());
}
}
URI uri = builder.build();
log.info("请求地址:" + uri);
httpGet.setURI(uri);
CloseableHttpResponse response = client.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
resultJson = EntityUtils.toString(response.getEntity(), encoding);
} else {
log.error("响应失败,状态码:" + status);
}
} catch (Exception var13) {
log.error("发送get请求失败", var13);
} finally {
httpGet.releaseConnection();
}
return resultJson;
}
public static String sendGet(String url, Map<String, Object> params) {
return sendGet(url, params, ENCODING);
}
public static String sendGet(String url) {
return sendGet(url, null, ENCODING);
}
}