最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Springboot整合xxljob,自定義添加、修改、刪除、停止、啟動任務(wù)方式

 更新時間:2025年04月29日 11:10:08   作者:藍(lán)眸少年CY  
這篇文章主要介紹了Springboot整合xxljob,自定義添加、修改、刪除、停止、啟動任務(wù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

本次自定義方式分為兩種:一種是模擬登錄,另一種是使用注解的方式

一、模擬登錄方式

修改xxl-job-admin工程,在controller里面添加一個MyApiController,在里面添加自定義的增刪等方法

@RestController
@RequestMapping("/api/myjobinfo")
public class MyApiController {

    private static Logger logger = LoggerFactory.getLogger(MyDynamicApiController.class);

    @Autowired
    private XxlJobService xxlJobService;

    @Autowired
    private LoginService loginService;
 
    @RequestMapping(value = "/pageList",method = RequestMethod.POST)
    public Map<String, Object> pageList(@RequestBody XxlJobQuery xxlJobQuery) {
        return xxlJobService.pageList(
                xxlJobQuery.getStart(),
                xxlJobQuery.getLength(),
                xxlJobQuery.getJobGroup(),
                xxlJobQuery.getTriggerStatus(),
                xxlJobQuery.getJobDesc(),
                xxlJobQuery.getExecutorHandler(),
                xxlJobQuery.getAuthor());
    }

    @PostMapping("/save")
    public ReturnT<String> add(@RequestBody(required = true)XxlJobInfo jobInfo) {
 
        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.GET)
    @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;
    }
}
  • 此方式優(yōu)點(diǎn):除了登錄接口為,其他接口都需要校驗
  • 缺點(diǎn):調(diào)用接口前需要登錄,比較繁瑣

二、注解方式

在項目中,有一個JobInfoController類,,這個類就是處理各種新增任務(wù),修改任務(wù),觸發(fā)任務(wù);但這些接口都是后臺管理頁面使用的,要想調(diào)用就必須要先登錄,也就是方式一,然而xxl-job已經(jīng)為我們提供了一個注解,通過這個注解的配置可以跳過登錄進(jìn)行訪問,這個注解就是 @PermissionLimit(limit = false) ,將limit設(shè)置為false即可,默認(rèn)是true,也就是需要做登錄驗證。我們可以在自己定義的Controller上使用這個注解。

@RestController
@RequestMapping("/api/myjobinfo")
public class MyApiController {

	@RequestMapping("/add")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> addJobInfo(@RequestBody XxlJobInfo jobInfo) {
		return xxlJobService.add(jobInfo);
	}

	@RequestMapping("/update")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> updateJobCron(@RequestBody XxlJobInfo jobInfo) {
		return xxlJobService.updateCron(jobInfo);
	}

	@RequestMapping("/remove")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> removeJob(@RequestBody XxlJobInfo jobInfo) {
		return xxlJobService.remove(jobInfo.getId());
	}

	@RequestMapping("/pauseJob")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> pauseJob(@RequestBody XxlJobInfo jobInfo) {
		return xxlJobService.stop(jobInfo.getId());
	}

	@RequestMapping("/start")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> startJob(@RequestBody XxlJobInfo jobInfo) {
		return xxlJobService.start(jobInfo.getId());
	}

    @RequestMapping("/stop")
	@ResponseBody
	public ReturnT<String> pause(int id) {
		return xxlJobService.stop(id);
	}

	@RequestMapping("/addAndStart")
	@ResponseBody
	@PermissionLimit(limit = false)
	public ReturnT<String> addAndStart(@RequestBody XxlJobInfo jobInfo) {
		ReturnT<String> result = xxlJobService.add(jobInfo);
		int id = Integer.valueOf(result.getContent());
		xxlJobService.start(id);
		return result;
	}

}
  • 該方式的優(yōu)點(diǎn):無需登錄可以直接調(diào)用接口
  • 缺點(diǎn):接口全部暴露有一定的風(fēng)險

將admin項目編譯打包后放入服務(wù)器,客戶端就可以開始調(diào)用了....

三、訪問者調(diào)用

1、創(chuàng)建實體

@Data
public class XxlJobInfo {
 
	private int id;				// 主鍵ID
	private int jobGroup;		// 執(zhí)行器主鍵ID
	private String jobDesc;     // 備注
	private String jobCron;
	private Date addTime;
	private Date updateTime;
	private String author;		// 負(fù)責(zé)人
	private String alarmEmail;	// 報警郵件
	private String scheduleType;			// 調(diào)度類型
	private String scheduleConf;			// 調(diào)度配置,值含義取決于調(diào)度類型
	private String misfireStrategy;			// 調(diào)度過期策略
	private String executorRouteStrategy;	// 執(zhí)行器路由策略
	private String executorHandler;		    // 執(zhí)行器,任務(wù)Handler名稱
	private String executorParam;		    // 執(zhí)行器,任務(wù)參數(shù)
	private String executorBlockStrategy;	// 阻塞處理策略
	private int executorTimeout;     		// 任務(wù)執(zhí)行超時時間,單位秒
	private int executorFailRetryCount;		// 失敗重試次數(shù)
	private String glueType;		// GLUE類型	#com.xxl.job.core.glue.GlueTypeEnum
	private String glueSource;		// GLUE源代碼
	private String glueRemark;		// GLUE備注
	private Date glueUpdatetime;	// GLUE更新時間
	private String childJobId;		// 子任務(wù)ID,多個逗號分隔
	private int triggerStatus;		// 調(diào)度狀態(tài):0-停止,1-運(yùn)行
	private long triggerLastTime;	// 上次調(diào)度時間
	private long triggerNextTime;	// 下次調(diào)度時間
}

2、創(chuàng)建一個工具類

也可以不創(chuàng)建直接調(diào)用

public class XxlJobUtil {
    private static String cookie="";
 
    /**
     * 查詢現(xiàn)有的任務(wù)
     * @param url
     * @param requestInfo
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public static JSONObject pageList(String url,JSONObject requestInfo) throws HttpException, IOException {
        String path = "/api/jobinfo/pageList";
        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);
        System.out.println(result.toJSONString());
        return result;
    }
 
 
    /**
     * 新增/編輯任務(wù)
     * @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);
        System.out.println(result.toJSONString());
        return result;
    }
 
    /**
     * 刪除任務(wù)
     * @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);
    }
 
    /**
     * 開始任務(wù)
     * @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);
    }
 
    /**
     * 停止任務(wù)
     * @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 postMethod, JSONObject result) throws IOException {
        if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String str;
            while((str = br.readLine()) != null){
                stringBuffer.append(str);
            }
            String response = new String(stringBuffer);
            br.close();
 
            return (JSONObject) JSONObject.parse(response);
        } else {
            return null;
        }
 
 
    }
 
    /**
     * 登錄
     * @param url
     * @param userName
     * @param password
     * @return
     * @throws HttpException
     * @throws IOException
     */
    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 get = new GetMethod((targetUrl));
        httpClient.executeMethod(get);
        if (get.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;
    }
}

如果是方式二可以直接調(diào)用,無需登錄

四、測試

如果是方式二,無需登錄,也就不用再請求頭里面設(shè)置cookie

@RestController
public class TestController {
 
    @Value("${xxl.job.admin.addresses:''}")
    private String adminAddresses;
 
    @Value("${xxl.job.admin.login-username:admin}")
    private String loginUsername;
 
    @Value("${xxl.job.admin.login-pwd:123456}")
    private String loginPwd;
 
    //登陸
    private void xxljob_login()
    {
        try {
            XxlJobUtil.login(adminAddresses,loginUsername,loginPwd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    @RequestMapping(value = "/pageList",method = RequestMethod.GET)
    public Object pageList() throws IOException {
        // int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author
        JSONObject test=new JSONObject();
        test.put("length",10);
        xxljob_login();
 
        JSONObject response = XxlJobUtil.pageList(adminAddresses, test);
        return  response.get("data");
    }
 
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public Object add() throws IOException {
        XxlJobInfo xxlJobInfo=new XxlJobInfo();
        xxlJobInfo.setJobCron("0/1 * * * * ?");
        xxlJobInfo.setJobGroup(3);
        xxlJobInfo.setJobDesc("Test XXl-job");
        xxlJobInfo.setAddTime(new Date());
        xxlJobInfo.setUpdateTime(new Date());
        xxlJobInfo.setAuthor("Test");
        xxlJobInfo.setAlarmEmail("1234567@com");
        xxlJobInfo.setScheduleType("CRON");
        xxlJobInfo.setScheduleConf("0/1 * * * * ?");
        xxlJobInfo.setMisfireStrategy("DO_NOTHING");
        xxlJobInfo.setExecutorRouteStrategy("FIRST");
        xxlJobInfo.setExecutorHandler("clockInJobHandler_1");
        xxlJobInfo.setExecutorParam("att");
        xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
        xxlJobInfo.setExecutorTimeout(0);
        xxlJobInfo.setExecutorFailRetryCount(1);
        xxlJobInfo.setGlueType("BEAN");
        xxlJobInfo.setGlueSource("");
        xxlJobInfo.setGlueRemark("初始化");
        xxlJobInfo.setGlueUpdatetime(new Date());
        JSONObject test = (JSONObject) JSONObject.toJSON(xxlJobInfo);
 
        xxljob_login();
        JSONObject response = XxlJobUtil.addJob(adminAddresses, test);
        if (response.containsKey("code") && 200 == (Integer) response.get("code")) {
            String jobId = response.getString("content");
            System.out.println("新增成功,jobId:" + jobId);
        } else {
            System.out.println("新增失敗");
        }
        return response;
    }
 
    @RequestMapping(value = "/stop/{jobId}",method = RequestMethod.GET)
    public void stop(@PathVariable("jobId") Integer jobId) throws IOException {
 
        xxljob_login();
        JSONObject response = XxlJobUtil.stopJob(adminAddresses, jobId);
        if (response.containsKey("code") && 200 == (Integer) response.get("code")) {
            System.out.println("任務(wù)停止成功");
        } else {
            System.out.println("任務(wù)停止失敗");
        }
    }
 
    @RequestMapping(value = "/delete/{jobId}",method = RequestMethod.GET)
    public void delete(@PathVariable("jobId") Integer jobId) throws IOException {
 
        xxljob_login();
        JSONObject response = XxlJobUtil.deleteJob(adminAddresses, jobId);
        if (response.containsKey("code") && 200 == (Integer) response.get("code")) {
            System.out.println("任務(wù)移除成功");
        } else {
            System.out.println("任務(wù)移除失敗");
        }
    }
 
    @RequestMapping(value = "/start/{jobId}",method = RequestMethod.GET)
    public void start(@PathVariable("jobId") Integer jobId) throws IOException {
 
        xxljob_login();
        JSONObject response = XxlJobUtil.startJob(adminAddresses, jobId);
        if (response.containsKey("code") && 200 == (Integer) response.get("code")) {
            System.out.println("任務(wù)啟動成功");
        } else {
            System.out.println("任務(wù)啟動失敗");
        }
    }
 
}

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 基于jstree使用JSON數(shù)據(jù)組裝成樹

    基于jstree使用JSON數(shù)據(jù)組裝成樹

    這篇文章主要為大家詳細(xì)介紹了基于jstree使用JSON數(shù)據(jù)組裝成樹,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • 在Java項目中實現(xiàn)日志輸出的技巧分享

    在Java項目中實現(xiàn)日志輸出的技巧分享

    日志是開發(fā)過程中不可或缺的一部分,它可以幫助我們追蹤代碼的執(zhí)行過程、排查問題以及監(jiān)控系統(tǒng)運(yùn)行狀況,然而,大多數(shù)開發(fā)人員在編寫日志時往往只關(guān)注于輸出必要的信息,而忽略了日志的可讀性和美觀性,本文將介紹如何在Java項目中實現(xiàn)漂亮的日志輸出
    2023-10-10
  • SpringBoot整合高德地圖實現(xiàn)天氣預(yù)報功能

    SpringBoot整合高德地圖實現(xiàn)天氣預(yù)報功能

    在當(dāng)今數(shù)字化時代,天氣預(yù)報功能在眾多應(yīng)用中扮演著重要角色,通過整合高德地圖提供的天氣API,我們可以輕松地在自己的SpringBoot項目中實現(xiàn)這一功能,本文將詳細(xì)介紹如何在SpringBoot項目中整合高德地圖的天氣預(yù)報功能,感興趣的小伙伴跟著小編一起來看看吧
    2025-03-03
  • SpringBoot集成kafka全面實戰(zhàn)記錄

    SpringBoot集成kafka全面實戰(zhàn)記錄

    在實際開發(fā)中,我們可能有這樣的需求,應(yīng)用A從TopicA獲取到消息,經(jīng)過處理后轉(zhuǎn)發(fā)到TopicB,再由應(yīng)用B監(jiān)聽處理消息,即一個應(yīng)用處理完成后將該消息轉(zhuǎn)發(fā)至其他應(yīng)用,完成消息的轉(zhuǎn)發(fā),這篇文章主要介紹了SpringBoot集成kafka全面實戰(zhàn),需要的朋友可以參考下
    2021-11-11
  • SpringBoot+log4j2.xml使用application.yml屬性值問題

    SpringBoot+log4j2.xml使用application.yml屬性值問題

    這篇文章主要介紹了SpringBoot+log4j2.xml使用application.yml屬性值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • @RequestMapping 如何使用@PathVariable 從URI中獲取參數(shù)

    @RequestMapping 如何使用@PathVariable 從URI中獲取參數(shù)

    這篇文章主要介紹了@RequestMapping 如何使用@PathVariable 從URI中獲取參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringBoot的監(jiān)控(Actuator)功能用法詳解

    SpringBoot的監(jiān)控(Actuator)功能用法詳解

    這篇文章主要介紹了SpringBoot的監(jiān)控(Actuator)功能用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • FactoryBean的使用及底層工作原理分析

    FactoryBean的使用及底層工作原理分析

    FactoryBean接口解析與使用示例,詳解Spring框架中FactoryBean的作用和底層原理,以及如何通過FactoryBean實現(xiàn)對象的動態(tài)創(chuàng)建is裝配is代理is包裝和生命周期管理
    2026-05-05
  • Java經(jīng)典設(shè)計模式之策略模式原理與用法詳解

    Java經(jīng)典設(shè)計模式之策略模式原理與用法詳解

    這篇文章主要介紹了Java經(jīng)典設(shè)計模式之策略模式,簡單說明了策略模式的概念、原理并結(jié)合實例形式分析了java策略模式的具有用法與相關(guān)注意事項,需要的朋友可以參考下
    2017-08-08
  • Java詳解AVL樹的應(yīng)用

    Java詳解AVL樹的應(yīng)用

    AVL樹是高度平衡的二叉樹,它的特點(diǎn)是AVL樹中任何節(jié)點(diǎn)的兩個子樹的高度最大差別為1,本文主要給大家介紹了Java如何實現(xiàn)AVL樹,需要的朋友可以參考下
    2022-07-07

最新評論

昭觉县| 河南省| 黎川县| 靖州| 莱芜市| 兰西县| 长宁县| 西宁市| 阿坝| 彰化县| 临泉县| 东莞市| 延庆县| 辽源市| 柏乡县| 山丹县| 巴里| 新乐市| 黄骅市| 河津市| 达尔| 寿光市| 宿州市| 北辰区| 叶城县| 澄城县| 云阳县| 罗甸县| 绥阳县| 孝感市| 车致| 中西区| 三原县| 遂平县| 炎陵县| 开鲁县| 会东县| 阿尔山市| 郸城县| 二连浩特市| 荔波县|