spring boot调用xxl-job对外接口

pom文件

<dependency>
    <groupId>com.xuxueli</groupId>
    <artifactId>xxl-job-core</artifactId>
    <version>${xxl-job.version}</version>
</dependency>

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

controller
在xxl-job-admin中新建一个controller,代码里面调用的就是这个controller

package com.xxl.job.admin.controller;

import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.cron.CronExpression;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.thread.JobScheduleHelper;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.service.LoginService;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;

/**
 * xxl-job代码自用接口
 */
@RestController
@RequestMapping("/api/jobinfo")
public class XxlJobAdminRestController {
    private static Logger logger = LoggerFactory.getLogger(XxlJobAdminRestController.class);

    @Autowired
    private XxlJobService xxlJobService;

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public ReturnT<String> add(@RequestBody(required = true) XxlJobInfo jobInfo) throws Exception {
        // next trigger time (5s后生效,避开预读周期)
        long nextTriggerTime = 0;
        try {
            Date nextValidTime = new CronExpression(jobInfo.getJobCron()).getNextValidTimeAfter(new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
            if (nextValidTime == null) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_never_fire"));
            }
            nextTriggerTime = nextValidTime.getTime();
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
            return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("jobinfo_field_cron_unvalid")+" | "+ e.getMessage());
        }

        jobInfo.setTriggerStatus(1);
        jobInfo.setTriggerLastTime(0);
        jobInfo.setTriggerNextTime(nextTriggerTime);

        jobInfo.setUpdateTime(new Date());

        if(jobInfo.getId()==0){
            return xxlJobService.add(jobInfo);
        }else{
            return xxlJobService.update(jobInfo);
        }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public ReturnT<String> delete(int id) {
        return xxlJobService.remove(id);
    }

    @RequestMapping(value = "/start",method = RequestMethod.GET)
    public ReturnT<String> start(int id) {
        return xxlJobService.start(id);
    }

    @RequestMapping(value = "/stop",method = RequestMethod.GET)
    public ReturnT<String> stop(int id) {
        return xxlJobService.stop(id);
    }

    @RequestMapping(value="/login", method=RequestMethod.POST)
    @PermissionLimit(limit=false)
    public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){
        boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false;
        ReturnT<String> result= loginService.login(request, response, userName, password, ifRem);
        return result;
    }

XxlJobUtil

 package com.cloud.busine.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Cookie;
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 java.io.IOException;

/**
 * xxl-job工具类
 */
public class XxlJobUtil {
    private static String cookie="";

    /**
     * 新增/编辑任务
     * @param url
     * @param requestInfo
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject addJob(String url,JSONObject requestInfo) throws HttpException, IOException {
        String path = "/api/jobinfo/save";
        String targetUrl = url + path;
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod(targetUrl);
        post.setRequestHeader("cookie", cookie);
        RequestEntity requestEntity = new StringRequestEntity(requestInfo.toString(), "application/json", "utf-8");
        post.setRequestEntity(requestEntity);
        httpClient.executeMethod(post);
        JSONObject result = new JSONObject();
        result = getJsonObject(post, result);
        return result;
    }

    /**
     * 删除任务
     * @param url
     * @param id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject deleteJob(String url,int id) throws HttpException, IOException {
        String path = "/api/jobinfo/delete?id="+id;
        return doGet(url,path);
    }

    /**
     * 开始任务
     * @param url
     * @param id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject startJob(String url,int id) throws HttpException, IOException {
        String path = "/api/jobinfo/start?id="+id;
        return doGet(url,path);
    }

    /**
     * 停止任务
     * @param url
     * @param id
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject stopJob(String url,int id) throws HttpException, IOException {
        String path = "/api/jobinfo/stop?id="+id;
        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 {
        if (get.getStatusCode() == 200) {
            String responseBodyAsString = get.getResponseBodyAsString();
            result = JSONObject.parseObject(responseBodyAsString);
        } else {
            try {
                result = JSONObject.parseObject(get.getResponseBodyAsString());
            } catch (Exception e) {
                result.put("error", get.getResponseBodyAsString());
            }
        }
        return result;
    }


    public static String login(String url, String userName, String password) throws HttpException, IOException {
        String path = "/api/jobinfo/login?userName="+userName+"&password="+password;
        String targetUrl = url + path;
        HttpClient httpClient = new HttpClient();
        HttpMethod post = new PostMethod(targetUrl);
        httpClient.executeMethod(post);
        if (post.getStatusCode() == 200) {
            Cookie[] cookies = httpClient.getState().getCookies();
            StringBuffer tmpcookies = new StringBuffer();
            for (Cookie c : cookies) {
                tmpcookies.append(c.toString() + ";");
            }
            cookie = tmpcookies.toString();
        } else {
            try {
                cookie = "";
            } catch (Exception e) {
                cookie="";
            }
        }
        return cookie;
    }
}

测试

public static void main(String[] args) throws IOException {
        try {
            JSONObject requestInfo = new JSONObject();
            requestInfo.put("jobGroup",1); // 执行器主键ID
            requestInfo.put("jobDesc","我是任务"); // 任务描述
            requestInfo.put("id", jobInfoId); // 任务ID不为空是表示修改任务
            requestInfo.put("executorRouteStrategy","FIRST"); //路由策略
            requestInfo.put("cronGen_display","0 0/1 * * * ?");
            requestInfo.put("jobCron","0 0/1 * * * ?"); // cron表达式
            requestInfo.put("glueType","BEAN"); // GLUE类型
            requestInfo.put("executorHandler","demoJobHandler"); // JobHandler名称
            requestInfo.put("executorBlockStrategy","SERIAL_EXECUTION"); // 阻塞处理策略
            requestInfo.put("executorTimeout",0); // 任务执行超时时间,单位秒
            requestInfo.put("executorFailRetryCount",1); // 失败重试次数
            requestInfo.put("author","admin"); //负责人
            requestInfo.put("alarmEmail","[email protected]"); //报警邮件
            requestInfo.put("executorParam","att"); //任务参数
            requestInfo.put("glueRemark","GLUE代码初始化"); // GLUE备注
            
            //登录xxl-job
            XxlJobUtil.login("http://127.0.0.1:8090/xxl-job-admin","admin","123456");
            
            JSONObject response = XxlJobUtil.addJob("http://127.0.0.1:8090/xxl-job-admin", requestInfo);
            if (response.containsKey("code") && 200 == (Integer) response.get("code")) {
                System.out.println("成功");
            } else {
                System.out.println("失败1");
            }
        } catch (Exception e) {
            System.out.println("失败2");
        }
}

原文链接:https://blog.csdn.net/m0_37527542/article/details/104468785

你可能感兴趣的:(spring,boot,java,spring,boot,xxl-job)