xxl-job使用spring端口(不額外占用端口)

前言

在使用xxl-job的過程中,需要給每個執(zhí)行器額外配置一個端
口(默認(rèn)9999),這導(dǎo)致服務(wù)除了web服務(wù)端口,
還要額外多占用一個端口,多少有些不爽,有沒有可能xxl直接
復(fù)用spring-boot所占用的端口吶?

EmbedServer

要想知道是否可行,首先得清楚為什么xxl-job要獨占一個端口

實際上,每個要執(zhí)行定時任務(wù)得微服務(wù)都是xxl-job的一個執(zhí)行器,
執(zhí)行器要與調(diào)度中心進(jìn)行通訊:接受調(diào)度指令/上傳日志文件/心跳
等,因此在xxl-job-core包中,會在初始化時啟動一個EmbedServer

img.png

其內(nèi)部開啟一個socket負(fù)責(zé)與調(diào)度中心通訊(主要是接受調(diào)度中心的指令),使用的網(wǎng)絡(luò)框架是netty


img_1.png

于是我們的服務(wù)往往呈現(xiàn)如下場景


img_2.png

那么問題來了,調(diào)度中心與執(zhí)行器通訊使用的什么協(xié)議吶?看一下netty的handler
就可得出結(jié)論,我們最熟悉的:HTTP

img_3.png

思路

既然調(diào)度中心的調(diào)度指令是通過http協(xié)議傳輸過來的,從理論來講完全可以讓調(diào)度中心
的請求發(fā)送到spring-boot的端口上,接受請求后按原來的執(zhí)行邏輯執(zhí)行對應(yīng)的代碼即可,
這樣EmbedServer就可以刪除,netty可以不用,最重要的是服務(wù)不會額外占用端口了

實現(xiàn)

spring接口

貼一下執(zhí)行器接受請求處理的核心代碼(EmbedHttpServerHandler中):

switch(uri){
        case"/beat": // 心跳
        return executorBiz.beat();
        case"/idleBeat": // 空閑心跳
        IdleBeatParam idleBeatParam=GsonTool.fromJson(requestData,IdleBeatParam.class);
        return executorBiz.idleBeat(idleBeatParam);
        case"/run": // 執(zhí)行任務(wù)
        TriggerParam triggerParam=GsonTool.fromJson(requestData,TriggerParam.class);
        return executorBiz.run(triggerParam);
        case"/kill": // 終止任務(wù)
        KillParam killParam=GsonTool.fromJson(requestData,KillParam.class);
        return executorBiz.kill(killParam);
        case"/log": // 獲取日志
        LogParam logParam=GsonTool.fromJson(requestData,LogParam.class);
        return executorBiz.log(logParam);
default:
        return new ReturnT<String>(ReturnT.FAIL_CODE,"invalid request, uri-mapping("+uri+") not found.");
        }

其實就是根據(jù)不同的接口uri做對應(yīng)的處理,一共五個接口,spring實現(xiàn)這5個接口再簡單不過了,
直接用@RequestMapping就可以了,但我采用的方式是使用spring的動態(tài)注冊接口工具RequestMappingHandlerMapping

代碼如下:


@Component
@Slf4j
public class JobServer {

    /**
     * 定義一個請求的前綴
     */
    @Value("${job.executor.pre}")
    private String pre;

    private ExecutorBiz executorBiz;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @PostConstruct
    public void init() throws NoSuchMethodException {
        // 初始化執(zhí)行器
        this.executorBiz = new ExecutorBizImpl();
        // 處理器
        final RequestHandler handler = new RequestHandler(this.executorBiz);
        // 回調(diào)處理方法
        final Method method =
                RequestHandler.class.getDeclaredMethod("invoke", HttpServletRequest.class, String.class);
        // 注冊路由和回調(diào)方法
        this.requestMappingHandlerMapping.registerMapping(
                RequestMappingInfo
                        .paths(this.pre + "/beat", this.pre + "/idleBeat", this.pre + "/run",
                                this.pre + "/kill", this.pre + "/log")
                        .methods(RequestMethod.POST).build(),
                handler,
                method);
    }

    @AllArgsConstructor
    private class RequestHandler {
        private ExecutorBiz executorBiz;

        /**
         * 客戶端接受中心調(diào)度請求處理
         */
        @ResponseBody
        public Object invoke(final HttpServletRequest request, @RequestBody final String body) throws Throwable {
            String uri = request.getRequestURI();
            uri = uri.replace(JobServer.this.pre, "");
            final String requestData = body;

            // services mapping
            try {
                switch (uri) {
                    case "/beat":
                        return this.executorBiz.beat();
                    case "/idleBeat":
                        final IdleBeatParam idleBeatParam = GsonTool.fromJson(requestData, IdleBeatParam.class);
                        return this.executorBiz.idleBeat(idleBeatParam);
                    case "/run":
                        final TriggerParam triggerParam = GsonTool.fromJson(requestData, TriggerParam.class);
                        return this.executorBiz.run(triggerParam);
                    case "/kill":
                        final KillParam killParam = GsonTool.fromJson(requestData, KillParam.class);
                        return this.executorBiz.kill(killParam);
                    case "/log":
                        final LogParam logParam = GsonTool.fromJson(requestData, LogParam.class);
                        return this.executorBiz.log(logParam);
                    default:
                        return new ReturnT<String>(ReturnT.FAIL_CODE,
                                "invalid request, uri-mapping(" + uri + ") not found.");
                }
            } catch (final Exception e) {
                JobServer.log.error(e.getMessage(), e);
                return new ReturnT<String>(ReturnT.FAIL_CODE, "request error:" + ThrowableUtil.toString(e));
            }
        }
    }
}

此時spring就擁有了與原netty一樣功能的5個接口,我還加了一個前綴,畢竟例如"/run"的接口地址太寬泛

注冊地址

有了五個接口,下一步就是讓調(diào)度中心發(fā)出指令時走這五個接口即可,如何實現(xiàn)吶?

調(diào)度中心中的注冊地址是自動注冊的,就是執(zhí)行器的ip+port,調(diào)度中心發(fā)送指令其實就是通過httpClient調(diào)用這個
地址再加上五個接口的uri,所以只要執(zhí)行器注冊時候注冊新的地址(spring的端口),事情就完美解決了

xxl-job-core中啟動netty服務(wù)成功時才會去調(diào)度中心注冊地址:


img_4.png

由于現(xiàn)在不需要netty了,所以這段要刪掉,但要保留注冊邏輯,并注冊我們的新地址,所以不可避免的要
修改xxl-job-core的代碼

修改XxlJobExecutorstart方法

public void start()throws Exception{

        // init logpath
        JobFileAppender.initLogPath(this.logPath);

        // init invoker, admin-client
        this.initAdminBizList(this.adminAddresses,this.accessToken);

        // init JobLogFileCleanThread
        JobLogFileCleanThread.getInstance().start(this.logRetentionDays);

        // init TriggerCallbackThread
        TriggerCallbackThread.getInstance().start();

        /** 這之下原來的代碼是initEmbedServer(address, ip, port, appname, accessToken),現(xiàn)在直接改為注冊 **/
        // get ip
        String ip=(this.ip!=null&&this.ip.trim().length()>0)?this.ip:IpUtil.getIp();
        // generate address,這里的port就是spring的port,并加入前綴
        String address=this.address;
        if(this.address==null||this.address.trim().length()==0){
        String ip_port_address=IpUtil.getIpPort(ip,this.port); // registry-address:default use address to registry , otherwise use ip:port if address is null
        address="http://{ip_port}".replace("{ip_port}",ip_port_address);
        }
        // start registry,開始注冊
        ExecutorRegistryThread.getInstance().start(this.appname,address+this.pre);
        }
解除注冊

XxlJobExecutordestroy方法,負(fù)責(zé)在執(zhí)行器關(guān)閉時關(guān)閉EmbedServer,由于現(xiàn)在EmbedServer
已刪除,所以只保留解除注冊和之后的邏輯即可

public void destroy(){
        // stop registry 原stopEmbedServer()
        ExecutorRegistryThread.getInstance().toStop();
// 其余保留

總結(jié)

到此就實現(xiàn)了xxl-job走spring的接口,不額外占用端口,好處顯而易見,但也有一點壞處:導(dǎo)致定時任務(wù)調(diào)度
共用了處理web請求的線程池,自行評估即可

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容