DriverJob.java 8.86 KB
package com.ruoyi.job;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.service.IDriverService;
import com.ruoyi.pojo.response.ResponseScheduling;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.ListUtils;
import org.apache.commons.math3.distribution.RealDistribution;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.redispre.GlobalRedisPreName.DRIVER_SCHEDULING_PRE;

/**
 * 该定时任务用户获取驾驶员信息
 *
 * @author 20412
 */
@Component("driverJob")
public class DriverJob implements InitializingBean {

    @Autowired
    private RedisCache redisCache;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private IDriverService driverService;

    @Value("${api.url.getDriverInfo}")
    private String getDriverInfoUrl;

    @Value("${api.url.getSchedulingInfo}")
    private String getSchedulingInfoUrl;

    @Value("${api.config.password}")
    private String password;

    @Value("${api.config.nonce}")
    private String nonce;

    private static IDriverService DRIVER_SERVICE;
    private static RedisCache REDIS_CACHE;
    private static RestTemplate RESTTEMPLATE;


    private static String GET_SCHEDULING_INFO_URL;
    private static String GET_DRIVER_INFO_URL;
    private static String PASSWORD;
    private static String NONCE;

    /**
     * 通过该定时任务获取驾驶员信息 并保存到数据库
     * 排班信息映射 20分钟更新一次
     */
    public void getDriverInfo(String params) throws Exception {
        try {
            String getDriverInfoUrl = String.format(GET_DRIVER_INFO_URL, params);
            long timestamp = System.currentTimeMillis();
            // 获取驾驶员信息
            List<Driver> drivers = getDrivers(getDriverInfoUrl, String.valueOf(timestamp));
            // 格式化请求
            String getSchedulingInfoUrl = String.format(GET_SCHEDULING_INFO_URL, "99", ConstDateUtil.formatDate("yyyyMMdd"), timestamp, NONCE, PASSWORD, getSHA1(getStringStringMap(String.valueOf(timestamp))));
            // 获取排班信息并存入redis
            saveSchedulingToRedis(getSchedulingInfoUrl, drivers,ConstDateUtil.formatDate("yyyyMMdd"));
            // 分片插入
            List<List<Driver>> splitList = ListUtils.splitList(drivers, 1000);
            System.out.println("开始更新数据-----");
            for (List<Driver> driverList : splitList) {
                DRIVER_SERVICE.insertDrivers(driverList);
            }
            System.out.println("数据更新完毕-----");
        } catch (Exception e) {
            System.out.println("执行失败:" + e.getMessage());
        }
        System.out.println("执行结束");
    }

    /**
     * 导入图片任务
     */
    public void importImages(){
        // TODO 获取用户列表 通过用户列表的jobCode来匹配对应的用户图像信息并保存到服务器

    }

    public Map<String, List<ResponseScheduling>> saveSchedulingToRedis(String getSchedulingInfoUrl, List<Driver> drivers,String dateKey) {
        List<ResponseScheduling> originSchedulingList = RESTTEMPLATE.exchange(
                getSchedulingInfoUrl,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ResponseScheduling>>() {
                }).getBody();

        Map<String, List<ResponseScheduling>> driverSchedulingMap = new HashMap<>();
        // 按照员工工号来获取排班信息
        originSchedulingList = originSchedulingList.stream()
                .map(subItem->{
                    subItem.setJobCode(subItem.getJsy().split("/")[0]);
                    return subItem;
                }).collect(Collectors.toList());
        // 以员工号为key存入排班集合
        originSchedulingList.stream().forEach(item -> {
            // 员工号为key
            String jobCode = item.getJsy().split("/")[0];
            item.setJobCode(jobCode);
            if (Objects.isNull(driverSchedulingMap.get(jobCode))) {
                List<ResponseScheduling> oneDriverSchedulings = new ArrayList<>();
                oneDriverSchedulings.add(item);
                driverSchedulingMap.put(jobCode, oneDriverSchedulings);
            } else {
                driverSchedulingMap.get(jobCode).add(item);
            }
        });
        // 存入数据库
//        DRIVER_SERVICE.saveDriverScheduling(originSchedulingList);
        // 存入redis
        REDIS_CACHE.setCacheMap(DRIVER_SCHEDULING_PRE + dateKey, driverSchedulingMap, 1, TimeUnit.DAYS);
        return driverSchedulingMap;
    }

    private List<Driver> getDrivers(String format, String timestamp) throws Exception {
        Map<String, String> configMap = getStringStringMap(timestamp);
        String sign = getSHA1(configMap);
        String url = format
                + "?timestamp=" + timestamp
                + "&nonce=" + NONCE
                + "&password=" + PASSWORD
                + "&sign=" + sign;
        //生成签名
        List<Driver> drivers = RESTTEMPLATE.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Driver>>() {
                }).getBody().stream().map(item ->{
                    item.setJobCode(item.getJobCode().split("-")[1]);
                    return item;
                }).collect(Collectors.toList());
        return drivers;
    }

    public Map<String, String> getStringStringMap(String timestamp) {
        Map<String, String> configMap = new HashMap<>(5);
        configMap.put("timestamp", String.valueOf(timestamp));
        configMap.put("nonce", NONCE);
        configMap.put("password", PASSWORD);
        return configMap;
    }


    /**
     * 获取签名
     *
     * @param map
     * @return
     * @throws Exception
     */
    public String getSHA1(Map<String, String> map) throws Exception {
        try {
            String[] array = new String[map.size()];
            map.values().toArray(array);
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            throw e;
        }


    }

//    public static void main(String[] args) throws Exception {
//        RestTemplate restTemplate1 = new RestTemplate();
////        String url = "http://101.95.136.206:9089/webservice/rest/person/company/%s";
//        String url = "http://101.95.136.206:9089/webservice/rest/schedule_real/sch_jk/%s/%s?timestamp=%d&nonce=%s&password=%s&sign=%s";
//
//        long timestamp = System.currentTimeMillis();
//        Map<String, String> configMap = new HashMap<>(5);
//        configMap.put("timestamp", String.valueOf(timestamp));
//        configMap.put("nonce", "NONCE");
//        configMap.put("password", "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464");
//        String format = String.format(url, "99", DateUtils.getDate("yyyyMMdd"), timestamp, "NONCE", "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464", getSHA1(configMap));
////        String sign = getSHA1(configMap);
////        String httpUrl = format
////                + "?timestamp=" + timestamp
////                + "&nonce=" + "NONCE"
////                + "&password=" + "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464"
////                + "&sign=" + sign;
//        Object forObject = restTemplate1.getForObject(format, Object.class);
//    }

    @Override
    public void afterPropertiesSet() throws Exception {
        GET_DRIVER_INFO_URL = getDriverInfoUrl;
        NONCE = nonce;
        PASSWORD = password;
        RESTTEMPLATE = restTemplate;
        DRIVER_SERVICE = driverService;
        REDIS_CACHE = redisCache;
        GET_SCHEDULING_INFO_URL = getSchedulingInfoUrl;
    }
}