附上使用文档,便于下次使用,:分布式任务调度平台XXL-JOB
一、定时器handler对应上图的jobHandler
@xxjob是将此方法扫描定时器
package com.xxl.job.executor.schedule.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.schedule.service.vehicle.VeBaseInfoService;
import com.xxl.job.executor.schedule.service.vehicle.VeLocationInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;
/**
* @param
* @author wdj
* @date 2022-7-7 15:07
* @desc 获取途强车辆信息定时任务
*/
@Component
@Primary
@Service
public class VehicleInfoHandler {
private static Logger logger = LoggerFactory.getLogger(VehicleInfoHandler.class);
@Autowired
private VeBaseInfoService veBaseInfoService;
@Autowired
private VeLocationInfoService veLocationInfoService;
@XxlJob("vehicleInfoHandler")
public ReturnT<String> execute() throws Exception {
try {
String params = XxlJobHelper.getJobParam();
veBaseInfoService.IncrementalVehicle(params);
veLocationInfoService.increaseVeLocationInfo(params);
veLocationInfoService.increaseTrackInfo(params);
SUCCESS.setMsg("任务执行成功");
} catch (Exception e) {
XxlJobHelper.log("异常:" + e.getMessage());
SUCCESS.setMsg("任务执行失败");
logger.error("任务执行失败:", e);
}
return SUCCESS;
}
}
二、访问第三方接口需要token,保存token到redis
package com.xxl.job.executor.schedule.service.impl.vehicle;
import com.xxl.job.executor.schedule.service.vehicle.VeAccessTokenService;
import com.xxl.job.executor.schedule.util.RedisTokenHelper;
import com.xxl.job.executor.schedule.util.jimiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @param
* @author wdj
* @date 2022-7-11 11:18
* @desc
*/
@Service
public class VeAccessTokenServiceImpl implements VeAccessTokenService {
@Autowired
private RedisTokenHelper redisTokenHelper;
@Override
public String getVehicleAccessToken() throws Exception {
String token= "";
try {
token= redisTokenHelper.getToken("token");
if(token==null||token.equals("")){
token=jimiUtil.getToken();
redisTokenHelper.save("token", token);
}
}catch (NullPointerException e){
token= jimiUtil.getToken();
redisTokenHelper.save("token", token);
}
return token;
}
}
三、redis工具类
package com.xxl.job.executor.schedule.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @param
* @author wdj
* @date 2022-7-11 10:01
* @desc Redis操作工具类
*/
@Component
public class RedisTokenHelper {
@Autowired
private RedisTemplate redisTemplate;
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.HOURS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 键值对存储 字符串 :有效时间120分钟
*@param tokenType Token的key
*@param Token Token的值
*/
public void save(String tokenType,String Token){
set(tokenType, Token, 2);
}
/**
* 根据key从redis获取value
*@param tokenType
*@return String
*/
public String getToken(String tokenType){
return (String)get(tokenType);
}
}
四、第三方接口工具类
package com.xxl.job.executor.schedule.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.executor.schedule.model.TrackInfo;
import com.xxl.job.executor.schedule.model.VeBaseInfo;
import com.xxl.job.executor.schedule.model.VeLocationInfo;
import org.apache.http.HttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author wdj
* @date 2022-7-7 12:02
* @desc 途强第三方接口工具类
*/
@Component
public class jimiUtil {
private static Logger logger = LoggerFactory.getLogger(jimiUtil.class);
/**
* 途强相关配置
*/
private static String appkey="";
private static String appSecret ="";
private static String serverUrl="http://open.aichezaixian.com/route/rest";
private static String user="";
private static String pwd="";
/**
* 获取Token
*
* @return
* @throws Exception
*/
public static String getToken() throws Exception {
Map<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Content-Type", "application/x-www-form-urlencoded");
Map<String, String> paramMap = new HashMap<>();
paramMap.put("method", "jimi.oauth.token.get");
// 私有参数
paramMap.put("user_id",user);
paramMap.put("user_pwd_md5", DigestUtils.md5Hex(pwd));
paramMap.put("expires_in", "7200");
paramMap=getPublicParams(paramMap);
paramMap.put("sign", SignUtils.signTopRequest(paramMap, appSecret, "md5"));
HttpPost post = new HttpPost(serverUrl);
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : paramMap.keySet()) {
list.add(new BasicNameValuePair(key, paramMap.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
if (null != headerMap) {
post.setHeaders(StringUtil.assemblyHeader(headerMap));
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
String postResult= EntityUtils.toString(entity, "utf-8");
JSONObject resultJson = JSON.parseObject(postResult);
JSONObject data = resultJson.getJSONObject("result");
String token = data.getString("accessToken");
String refreshToken=data.getString("refreshToken");
return token;
}
/*
1. @Description: 获取该账户下的所有IMEI信息
2. @Param:
3. @return:
4. @Author: wdj
5. @Date: 2022-7-7
*/
public static List<VeBaseInfo> getDeviceList(String token) throws Exception {
Map<String, String> paramMap =new HashMap<String, String>();
// 私有参数
paramMap.put("access_token",token);
paramMap.put("method", "jimi.user.device.list");
paramMap.put("target",user);
String result =sendPost(paramMap);
JSONObject resultJson = JSON.parseObject(result);
JSONArray array = resultJson.getJSONArray("result");
return jimiUtil.convertVeBaseInfo(array);
}
/*
1. @Description: 根据账户,获取该账户下所有IMEI的最新定位数据
2. @Param:
3. @return:
4. @Author: wdj
5. @Date: 2022-7-11
*/
public static List<VeLocationInfo> getLocationList(String token) throws Exception {
Map<String, String> paramMap =new HashMap<String, String>();
// 私有参数
paramMap.put("access_token",token);
paramMap.put("method", "jimi.user.device.location.list");
paramMap.put("target",user);
String result =sendPost(paramMap);
JSONObject resultJson = JSON.parseObject(result);
JSONArray array = resultJson.getJSONArray("result");
return jimiUtil.convertVeLocationInfo(array);
}
/*
1. @Description: 根据IMEI获取轨迹数据
2. @Param:token秘钥,
imei设备编号,
begin_time 格式为yyyy-MM-dd HH:mm:ss,
end_time 结束时间,格式为yyyy-MM-dd HH:mm:ss end_time不应大于当前时间。
3. @return:
4. @Author: wdj
5. @Date: 2022-7-11
*/
public static JSONArray getTrajectoryData(String imei,String begin_time,String end_time,String token) throws Exception{
Map<String, String> paramMap =new HashMap<String, String>();
// 私有参数
paramMap.put("access_token",token);
paramMap.put("imei",imei);
paramMap.put("begin_time",begin_time);
paramMap.put("end_time",end_time);
paramMap.put("method", "jimi.device.track.list");
paramMap.put("target",user);
String result =sendPost(paramMap);
JSONObject resultJson = JSON.parseObject(result);
JSONArray array = resultJson.getJSONArray("result");
return array;//jimiUtil.convertTrackInfo(array);
}
public static String sendPost(Map<String, String> paramMap)throws Exception {
String resu = null;//返回参数
try {
Map<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Content-Type", "application/x-www-form-urlencoded");
paramMap= getPublicParams(paramMap);//组装参数
paramMap.put("sign", SignUtils.signTopRequest(paramMap, appSecret, "md5"));
//发送请求
HttpPost post = new HttpPost(serverUrl);
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : paramMap.keySet()) {
list.add(new BasicNameValuePair(key, paramMap.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
if (null != headerMap) {
post.setHeaders(StringUtil.assemblyHeader(headerMap));
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
resu = EntityUtils.toString(entity, "utf-8");
} catch (IOException e) {
logger.info(e.getMessage());
}
return resu;
}
/*
1. @Description: 获取公共参数
2. @Param:
3. @return:
4. @Author: wdj
5. @Date: 2022-7-7
*/
public static Map<String, String> getPublicParams(Map<String, String> paramMap) throws IOException {
// 公共参数
paramMap.put("app_key", appkey);
paramMap.put("v", "1.0");
paramMap.put("timestamp", StringUtil.getCurrentDate());
paramMap.put("sign_method", "md5");
paramMap.put("format", "json");
return paramMap;
}
private static List<VeBaseInfo> convertVeBaseInfo(JSONArray jsonArray) {
List<VeBaseInfo> veBaseInfoList=new ArrayList<VeBaseInfo>();
//遍历json集合,取出数据
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject result = (JSONObject) jsonArray.get(i);
VeBaseInfo veBaseInfo = new VeBaseInfo();
veBaseInfo.setImei(result.getString("imei"));
veBaseInfo.setDeviceName(result.getString("deviceName"));
veBaseInfo.setMcType(result.getString("mcType"));
veBaseInfo.setSim(result.getString("sim"));
veBaseInfo.setVehicleIcon(result.getString("vehicleIcon"));
veBaseInfo.setVehicleName(result.getString("vehicleName"));
veBaseInfo.setVehicleModels(result.getString("vehicleModels"));
veBaseInfo.setDriverName(result.getString("driverName"));
veBaseInfo.setCarFrame(result.getString("carFrame"));
veBaseInfo.setDriverPhone(result.getString("driverPhone"));
veBaseInfo.setEnabledFlag(result.getLong("enabledFlag"));
veBaseInfo.setEngineNumber(result.getString("engineNumber"));
veBaseInfoList.add(veBaseInfo);
}
return veBaseInfoList;
}
private static List<VeLocationInfo> convertVeLocationInfo(JSONArray jsonArray) {
List<VeLocationInfo> veLocationInfos=new ArrayList<VeLocationInfo>();
//遍历json集合,取出数据
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject result = (JSONObject) jsonArray.get(i);
VeLocationInfo veLocationInfo = new VeLocationInfo();
veLocationInfo.setImei(result.getString("imei"));
veLocationInfo.setDeviceName(result.getString("deviceName"));
veLocationInfo.setIcon(result.getString("icon"));
veLocationInfo.setStatus(result.getString("status"));
veLocationInfo.setLat(result.getLong("lat"));
veLocationInfo.setLng(result.getLong("lng"));
veLocationInfo.setExpireFlag(result.getString("expireFlag"));
veLocationInfo.setActivationFlag(result.getString("activationFlag"));
veLocationInfo.setPosType(result.getString("posType"));
veLocationInfo.setGpsTime(result.getString("gpsTime"));
veLocationInfo.setHbTime(result.getString("hbTime"));
veLocationInfo.setSpeed(result.getString("speed"));
veLocationInfo.setAccStatus(result.getString("accStatus"));
veLocationInfo.setElectQuantity(result.getString("electQuantity"));
veLocationInfo.setPowerValue(result.getString("powerValue"));
veLocationInfo.setGpsNum(result.getString("gpsNum"));
veLocationInfo.setDirection(result.getString("direction"));
veLocationInfo.setMileage(result.getString("mileage"));
veLocationInfos.add(veLocationInfo);
}
return veLocationInfos;
}
/*
1. @Description: 轨迹数组转换为list
2. @Param:
3. @return:
4. @Author: wdj
5. @Date: 2022-7-11
*/
private static List<TrackInfo> convertTrackInfo(JSONArray jsonArray) {
List<TrackInfo> trackInfos=new ArrayList<TrackInfo>();
//遍历json集合,取出数据
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject result = (JSONObject) jsonArray.get(i);
TrackInfo trackInfo = new TrackInfo();
trackInfo.setLat(result.getDouble("lat"));
trackInfo.setLng(result.getDouble("lng"));
trackInfo.setGpsTime(result.getString("gpsTime"));
trackInfo.setDirection(result.getString("direction"));
trackInfo.setDirection(result.getString("direction"));
trackInfo.setGpsSpeed(result.getString("gpsSpeed"));
trackInfo.setPosType(result.getString("posType"));
trackInfos.add(trackInfo);
}
return trackInfos;
}
}