调用接口创建,启动,挂起,删除 xxljob任务

举报
小小张自由--张有博 发表于 2022/03/30 18:29:38 2022/03/30
【摘要】 调用接口创建,启动,挂起,删除 xxljob任务

1.引入依赖

 <!--针对自己项目的xxl-job-core进行引入即可-->
        <dependency>
            <groupId>com.xuxueli</groupId>
            <artifactId>xxl-job-core</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!--org.apache.commons.httpclient-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
   

2.添加配置项

xxl:
  job:
    admin:
      # xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
      # xxl-job-admin 启动地址
      addresses: http://d-xxljob.dmsd.tech:8081/job-admin-dev
    # xxl-job, access token
    accessToken:
    executor:
      # xxl-job executor appname 手动配置的客户端名称
      appname: ar-test
      # xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
      address:
      # xxl-job executor server-info 可以自动分配地址进行注册
      ip:
      port: 9998
      # xxl-job executor log-path
      logpath: /data/xxl-job/jobhandler
      # xxl-job executor log-retention-days
      logretentiondays: 30

xxljob:
  userName: admin
  password: 123456
  ifRemember: on

3.创建工具类XxlJobUtil,TimeUtil

package com.tfjy.arprobackend.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 操作xxl-job的工具类
 *
 * @author Promsing(张有博)
 * @version 1.0.0
 * @since 2022/3/30 - 15:08
 */
@Component
public class XxlJobUtil {


    private static String cookie="";

    private static RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 新增/编辑任务
     * @param requestInfo
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject addJob( MultiValueMap requestInfo) throws HttpException, IOException {
        //1.拼接url
        String path = "/jobinfo/add";
        String targetUrl = GlobalEnvironment.getConfig("xxl.job.admin.addresses") + path;

        //2.获得cookie
        String cookie = XxlJobUtil.login();

        //2.封装请求格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookie);
        HttpEntity httpEntity=new HttpEntity(requestInfo,headers);

        //4.发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(targetUrl, org.springframework.http.HttpMethod.POST, httpEntity, String.class);

        //5.返回结果集     "code": 200,"msg": null, "content": "任务id"
        String body = exchange.getBody();
        JSONObject result = JSONObject.parseObject(body);
        return result;

    }

    public static JSONObject updateJob(String url, MultiValueMap requestInfo) throws HttpException, IOException {
        String path = "/jobinfo/update";
        String targetUrl = url + path;
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod(targetUrl);
        RequestEntity requestEntity = new StringRequestEntity(requestInfo.toString(), MediaType.APPLICATION_FORM_URLENCODED_VALUE, "utf-8");
        post.setRequestEntity(requestEntity);
        httpClient.executeMethod(post);
        JSONObject result = new JSONObject();
        result = getJsonObject(post, result);
        return result;
    }

    /**
     * 删除任务
     * @param id 任务id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject deleteJob(int id) throws HttpException, IOException {
        //TODO: 请求无返回值,任务删除成功。
        //1.拼接URL
        String path = "/jobinfo/remove";
        String url = GlobalEnvironment.getConfig("xxl.job.admin.addresses");
        String targetUrl = url + path;

        //2.获得cookie
        String cookie = XxlJobUtil.login();

        //3.封装请求参数
        MultiValueMap requestInfo=new LinkedMultiValueMap();
        requestInfo.add("id",id);

        //4.封装请求格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookie);
        HttpEntity httpEntity=new HttpEntity(requestInfo,headers);

        //5.发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(targetUrl, org.springframework.http.HttpMethod.POST, httpEntity, String.class);

        //6.返回结果集     "code": 200,"msg": null, "content": null
        String body = exchange.getBody();
        JSONObject result = JSONObject.parseObject(body);
        return result;

    }

    /**
     * 开始任务
     * @param id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject startJob(int id) throws HttpException, IOException {

        //1.拼接URL
        String path = "/jobinfo/start";
        String url = GlobalEnvironment.getConfig("xxl.job.admin.addresses");
        String targetUrl = url + path;

        //2.获得cookie
        String cookie = XxlJobUtil.login();

        //3.封装请求参数
        MultiValueMap requestInfo=new LinkedMultiValueMap();
        requestInfo.add("id",id);

        //4.封装请求格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookie);
        HttpEntity httpEntity=new HttpEntity(requestInfo,headers);

        //5.发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(targetUrl, org.springframework.http.HttpMethod.POST, httpEntity, String.class);

        //6.返回结果集     "code": 200,"msg": null, "content": null
        String body = exchange.getBody();
        JSONObject result = JSONObject.parseObject(body);
        return result;



    }

    /**
     * 停止任务
     * @param id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject stopJob(int id) throws HttpException, IOException {


        //1.拼接URL
        String path = "/jobinfo/stop";
        String url = GlobalEnvironment.getConfig("xxl.job.admin.addresses");
        String targetUrl = url + path;

        //2.获得cookie
        String cookie = XxlJobUtil.login();

        //3.封装请求参数
        MultiValueMap requestInfo=new LinkedMultiValueMap();
        requestInfo.add("id",id);

        //4.封装请求格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookie);
        HttpEntity httpEntity=new HttpEntity(requestInfo,headers);

        //5.发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(targetUrl, org.springframework.http.HttpMethod.POST, httpEntity, String.class);

        //6.返回结果集     "code": 200,"msg": null, "content": null
        String body = exchange.getBody();
        JSONObject result = JSONObject.parseObject(body);
        return result;

    }

    /**
     * 根据xxl-appname获取对应id
     * @param url
     * @param appnameParam
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject getAppNameIdByAppname(String url,String appnameParam) throws HttpException, IOException {
        String path = "/jobgroup/getAppNameIdByAppname?appnameParam="+appnameParam;
        return doGet(url,path);
    }

    public static JSONObject doGet(String url,String path) throws HttpException, IOException {
        String targetUrl = url + path;
        HttpClient httpClient = new HttpClient();
        HttpMethod get = new GetMethod(targetUrl);
        get.setRequestHeader("cookie", cookie);
        httpClient.executeMethod(get);
        JSONObject result = new JSONObject();
        result = getJsonObject(get, result);
        return result;
    }

    private static JSONObject getJsonObject(HttpMethod get, JSONObject result) throws IOException {
        InputStream inputStream = get.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String str = "";
        while ((str = br.readLine()) != null) {
            stringBuffer.append(str);
        }
        if (get.getStatusCode() == 200) {
            /**
             *  使用此方式会出现
             *  Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
             *  异常
             *  String responseBodyAsString = get.getResponseBodyAsString();
             *  result = JSONObject.parseObject(responseBodyAsString);*/
            result = JSONObject.parseObject(stringBuffer.toString());
        } else {
            try {
//                result = JSONObject.parseObject(get.getResponseBodyAsString());
                result = JSONObject.parseObject(stringBuffer.toString());
            } catch (Exception e) {
                result.put("error", stringBuffer.toString());
            }
        }
        return result;
    }


    /**
     * 登录xxl-job
     * @return 返回cookie
     */
    public static String login()  {
        //1.拼接URL
        String path = "/login";
        String url = GlobalEnvironment.getConfig("xxl.job.admin.addresses");
        String targetUrl = url + path;

        //2.封装参数
        MultiValueMap requestInfo=new LinkedMultiValueMap();
        requestInfo.add("userName",GlobalEnvironment.getConfig("xxljob.userName"));
        requestInfo.add("password",GlobalEnvironment.getConfig("xxljob.password"));
        requestInfo.add("ifRemember",GlobalEnvironment.getConfig("xxljob.ifRemember"));

        //3.封装请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity httpEntity=new HttpEntity(requestInfo,headers);

        //4.发送请求,返回Cookie
        ResponseEntity<String> exchange = restTemplate.exchange(targetUrl, org.springframework.http.HttpMethod.POST, httpEntity, String.class);
        List<String> list = exchange.getHeaders().get("Set-Cookie");
        return list.get(0);

    }

}
package com.tfjy.arprobackend.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 时间转corn
 *
 * @author Promsing(张有博)
 * @version 1.0.0
 * @since 2022/3/30 - 15:09
 */
public class TimeUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
    /***
     *  功能描述:日期转换cron表达式
     * @param date
     * @return
     */
    public static String formatDateByPattern(Date date) {
        String formatTimeStr = null;
        if (Objects.nonNull(date)) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
}

4.编写controller类

package com.tfjy.arprobackend.controller;

import com.alibaba.fastjson.JSONObject;
import com.tfjy.arprobackend.utils.FrontResult;
import com.tfjy.arprobackend.utils.TimeUtil;
import com.tfjy.arprobackend.utils.XxlJobUtil;
import com.tfjy.arprobackend.utils.codeEnum.ResultCodeEnum;
import com.tfjy.arprobackend.utils.codeEnum.ResultMsgEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * XxlJOBController
 *
 * @author Promsing(张有博)
 * @version 1.0.0
 * @since 2022/3/30 - 15:04
 */
@Api(tags = {"操作xxljob的业务类"})
@RequestMapping(value = "/XxlJobController")
@RestController
public class XxlJobController {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;
    @Value("${xxl.job.executor.appname}")
    private String executorAppname;

    @ApiOperation(value = "添加jobInfo并启动", httpMethod = "GET")
    @GetMapping
    public FrontResult saveXxl() {
        //查询列表数据
        try {
            MultiValueMap requestInfo = new LinkedMultiValueMap();
            // 执行器主键ID
            requestInfo.add("jobGroup", 111);
            // 任务执行CRON表达式
            long etime1 = System.currentTimeMillis() + 1 * 60 * 1000;//延时函数,单位毫秒,这里是延时了1分钟
            String date = TimeUtil.formatDateByPattern(new Date(etime1));
            System.out.println(date);
//        requestInfo.put("jobCron","0 0/1 * * * ?");
            requestInfo.add("jobCron", date);
            // 任务描述
            requestInfo.add("jobDesc", "xxxJob");

            // 负责人
            requestInfo.add("author", "admin");
            // 报警邮件
            requestInfo.add("alarmEmail", "xxx@satcloud.com.cn");

            // 执行器路由策略
            requestInfo.add("executorRouteStrategy", "FIRST");
            // 执行器,任务Handler名称
            requestInfo.add("executorHandler", "xxxJobHandler");
            // todo 执行器,任务参数
            requestInfo.add("executorParam", "测试202006300943");
            // 阻塞处理策略
            requestInfo.add("executorBlockStrategy", "SERIAL_EXECUTION");
            // 任务执行超时时间,单位秒
            requestInfo.add("executorTimeout", 0);
            // 失败重试次数
            requestInfo.add("executorFailRetryCount", 1);
            // GLUE类型    #com.xxl.job.core.glue.GlueTypeEnum
            requestInfo.add("glueType", "BEAN");
            // GLUE备注
            requestInfo.add("glueRemark", "GLUE代码初始化");


            JSONObject FrontResultonse = XxlJobUtil.addJob( requestInfo);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
                //修改任务参数 把id放入
                // 执行器主键ID
                requestInfo.put("executorParam", "JobId=" + FrontResultonse.get("content") + ";测试202006300943");
                requestInfo.put("id", Integer.valueOf(FrontResultonse.get("content").toString()));
                JSONObject FrontResultonseUpdate = XxlJobUtil.updateJob(adminAddresses, requestInfo);
                if (FrontResultonseUpdate.containsKey("code") && 200 == (Integer) FrontResultonseUpdate.get("code")) {
                    //加入任务成功之后直接启动
                    JSONObject FrontResultonseStart = XxlJobUtil.startJob( Integer.valueOf(FrontResultonse.get("content").toString()));
                    if (FrontResultonseStart.containsKey("code") && 200 == (Integer) FrontResultonseStart.get("code")) {
                       return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "创建成功");
                    } else {
                        throw new Exception("调用xxl-job-admin-start接口失败!");
                    }
                } else {
                    throw new Exception("调用xxl-job-admin-update接口失败!");
                }
            } else {
                throw new Exception("调用xxl-job-admin-add接口失败!");
            }
        } catch (Exception e) {
            //No HttpMessageConverter for com.alibaba.fastjson.JSONObject and content type "application/x-www-form-urlencoded"
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 删除任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public FrontResult delete(int id) {
        try {
            JSONObject FrontResultonse = XxlJobUtil.deleteJob( id);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
               return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "删除成功");
            } else {
                throw new Exception("调用xxl-job-admin-delete接口失败!");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }

    }

    /**
     * 开始任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public FrontResult start(int id) {
        try {
            JSONObject result = XxlJobUtil.startJob( id);
            if (result.containsKey("code") && 200 == (Integer) result.get("code")) {
               return FrontResult.getSuccessResult(ResultMsgEnum.EXECUTE_SUCCESS.getMsg(), "开始Job任务成功,id"+id);
            } else {
                throw new Exception("调用xxl-job-admin-start接口失败!");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.EXECUTE_FAIL.getMsg());
        }

    }

    /**
     * 挂起任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/stop", method = RequestMethod.GET)
    public FrontResult stop(int id) {
        try {
            JSONObject FrontResultonse = XxlJobUtil.stopJob( id);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
               return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "挂起job任务成功,id"+id);
            } else {
                throw new Exception("调用xxl-job-admin-stop接口失败!");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 登录xxl-job
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public FrontResult login() {
        try {
            String cookie = XxlJobUtil.login();
            if (StringUtils.isNotBlank(cookie)) {
               return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), cookie);
            } else {
                throw new Exception("调用xxl-job-admin-login接口失败!");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 根据xxl-appname获取对应id
     *
     * @return
     * @throws
     */
    @RequestMapping(value = "/getAppNameIdByAppname", method = RequestMethod.GET)
    public FrontResult getAppNameIdByAppname() {
        try {
            JSONObject FrontResultonse = XxlJobUtil.getAppNameIdByAppname(adminAddresses,executorAppname);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
               return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "根据xxl-appname获取对应id");
            } else {
                throw new Exception("调用xxl-job-admin-getAppNameIdByAppname接口失败!");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

}

5.完成

通过测试调用接口,登录,新增,启动,停止,删除无问题。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。