本次自定义方式分为两种:一种是模拟登录,另一种是使用注解的方式
一、模拟登录方式
修改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;
}
}- 此方式优点:除了登录接口为,其他接口都需要校验
- 缺点:调用接口前需要登录,比较繁琐
二、注解方式
在项目中,有一个jobinfocontroller类,,这个类就是处理各种新增任务,修改任务,触发任务;但这些接口都是后台管理页面使用的,要想调用就必须要先登录,也就是方式一,然而xxl-job已经为我们提供了一个注解,通过这个注解的配置可以跳过登录进行访问,这个注解就是 @permissionlimit(limit = false) ,将limit设置为false即可,默认是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;
}
}- 该方式的优点:无需登录可以直接调用接口
- 缺点:接口全部暴露有一定的风险
将admin项目编译打包后放入服务器,客户端就可以开始调用了....
三、访问者调用
1、创建实体
@data
public class xxljobinfo {
private int id; // 主键id
private int jobgroup; // 执行器主键id
private string jobdesc; // 备注
private string jobcron;
private date addtime;
private date updatetime;
private string author; // 负责人
private string alarmemail; // 报警邮件
private string scheduletype; // 调度类型
private string scheduleconf; // 调度配置,值含义取决于调度类型
private string misfirestrategy; // 调度过期策略
private string executorroutestrategy; // 执行器路由策略
private string executorhandler; // 执行器,任务handler名称
private string executorparam; // 执行器,任务参数
private string executorblockstrategy; // 阻塞处理策略
private int executortimeout; // 任务执行超时时间,单位秒
private int executorfailretrycount; // 失败重试次数
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; // 子任务id,多个逗号分隔
private int triggerstatus; // 调度状态:0-停止,1-运行
private long triggerlasttime; // 上次调度时间
private long triggernexttime; // 下次调度时间
}2、创建一个工具类
也可以不创建直接调用
public class xxljobutil {
private static string cookie="";
/**
* 查询现有的任务
* @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;
}
/**
* 新增/编辑任务
* @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;
}
/**
* 删除任务
* @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 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;
}
}如果是方式二可以直接调用,无需登录
四、测试
如果是方式二,无需登录,也就不用再请求头里面设置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("任务停止成功");
} else {
system.out.println("任务停止失败");
}
}
@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("任务移除成功");
} else {
system.out.println("任务移除失败");
}
}
@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("任务启动成功");
} else {
system.out.println("任务启动失败");
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论