瀏覽代碼

- 1、调度中心迁移到 springboot;

xuxueli 6 年之前
父節點
當前提交
443c946e55
共有 28 個文件被更改,包括 322 次插入1218 次删除
  1. 13 11
      doc/XXL-JOB官方文档.md
  2. 28 0
      xxl-job-admin/pom.xml
  3. 9 44
      xxl-job-admin/src/main/java/com/xxl/job/admin/controller/JobApiController.java
  4. 3 3
      xxl-job-admin/src/main/java/com/xxl/job/admin/controller/interceptor/PermissionInterceptor.java
  5. 56 27
      xxl-job-admin/src/main/java/com/xxl/job/admin/core/schedule/XxlJobDynamicScheduler.java
  6. 1 1
      xxl-job-admin/src/main/java/com/xxl/job/admin/core/trigger/XxlJobTrigger.java
  7. 1 1
      xxl-job-admin/src/main/resources/application.properties
  8. 10 3
      xxl-job-admin/src/test/java/com/xxl/job/adminbiz/AdminBizTest.java
  9. 4 25
      xxl-job-core/pom.xml
  10. 94 27
      xxl-job-core/src/main/java/com/xxl/job/core/executor/XxlJobExecutor.java
  11. 0 92
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/codec/RpcRequest.java
  12. 0 41
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/codec/RpcResponse.java
  13. 0 81
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/NetComClientProxy.java
  14. 0 84
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/NetComServerFactory.java
  15. 0 48
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/client/JettyClient.java
  16. 0 92
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/server/JettyServer.java
  17. 0 68
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/server/JettyServerHandler.java
  18. 0 62
      xxl-job-core/src/main/java/com/xxl/job/core/rpc/serialize/HessianSerializer.java
  19. 3 12
      xxl-job-core/src/main/java/com/xxl/job/core/thread/ExecutorRegistryThread.java
  20. 0 110
      xxl-job-core/src/main/java/com/xxl/job/core/util/HttpClientUtil.java
  21. 0 135
      xxl-job-core/src/main/java/com/xxl/job/core/util/IpUtil.java
  22. 0 70
      xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java
  23. 22 47
      xxl-job-executor-samples/xxl-job-executor-sample-jfinal/src/main/java/com/xuxueli/executor/sample/jfinal/jobhandler/HttpJobHandler.java
  24. 22 44
      xxl-job-executor-samples/xxl-job-executor-sample-nutz/src/main/java/com/xuxueli/executor/sample/nutz/jobhandler/HttpJobHandler.java
  25. 22 44
      xxl-job-executor-samples/xxl-job-executor-sample-spring/src/main/java/com/xxl/job/executor/service/jobhandler/HttpJobHandler.java
  26. 7 2
      xxl-job-executor-samples/xxl-job-executor-sample-spring/src/test/java/com/xxl/executor/test/DemoJobHandlerTest.java
  27. 5 0
      xxl-job-executor-samples/xxl-job-executor-sample-springboot/pom.xml
  28. 22 44
      xxl-job-executor-samples/xxl-job-executor-sample-springboot/src/main/java/com/xxl/job/executor/service/jobhandler/HttpJobHandler.java

+ 13 - 11
doc/XXL-JOB官方文档.md 查看文件

@@ -1324,17 +1324,19 @@ Tips: 历史版本(V1.3.x)目前已经Release至稳定版本, 进入维护阶段
1324 1324
 - 41、docker支持:调度中心提供 Dockerfile 方便快速构建docker镜像; 
1325 1325
 
1326 1326
 ### 6.23 版本 V2.0.0 特性[迭代中]
1327
-- 1、[迭代中]调度中心迁移到springboot;
1328
-- 2、[迭代中]SimpleTrigger 支持;
1329
-- 3、[迭代中]任务状态与quartz解耦,降低quartz调度压力,仅NORMAL状态任务绑定quartz;
1330
-- 4、[迭代中]新增任务默认运行状态,任务更新时运行状态保持不变;
1331
-- 5、[迭代中]任务权限管理:执行器为粒度分配权限,核心操作校验权限;
1332
-- 6、[迭代中]Release发布时,一同发布调度中心安装包,真正实现开箱即用;
1333
-- 7、[迭代中]docker镜像,并且推送docker镜像到中央仓库,更进一步实现产品开箱即用;
1334
-- 8、[迭代中]cron在线生成工具,如 "cronboot/cron.qqe2";
1335
-- 9、[迭代中]原生提供通用命令行任务Handler(Bean任务,"CommandJobHandler");业务方只需要提供命令行即可,可执行任意命令;
1336
-- 10、IP获取逻辑优化,优先遍历网卡来获取可用IP;
1337
-- 11、任务新增的API服务接口返回任务ID,方便调用方实用;
1327
+- 1、调度中心迁移到 springboot;
1328
+- 2、底层通讯组件迁移至 xxl-rpc;
1329
+- 3、IP获取逻辑优化,优先遍历网卡来获取可用IP;
1330
+- 4、任务新增的API服务接口返回任务ID,方便调用方实用;
1331
+- 5、[迭代中]SimpleTrigger 支持;
1332
+- 6、[迭代中]任务状态与quartz解耦,降低quartz调度压力,仅NORMAL状态任务绑定quartz;
1333
+- 7、[迭代中]新增任务默认运行状态,任务更新时运行状态保持不变;
1334
+- 8、[迭代中]任务权限管理:执行器为粒度分配权限,核心操作校验权限;
1335
+- 9、[迭代中]Release发布时,一同发布调度中心安装包,真正实现开箱即用;
1336
+- 10、[迭代中]docker镜像,并且推送docker镜像到中央仓库,更进一步实现产品开箱即用;
1337
+- 11、[迭代中]cron在线生成工具,如 "cronboot/cron.qqe2";
1338
+- 12、[迭代中]原生提供通用命令行任务Handler(Bean任务,"CommandJobHandler");业务方只需要提供命令行即可,可执行任意命令;
1339
+
1338 1340
 
1339 1341
 ### TODO LIST
1340 1342
 - 1、任务分片路由:分片采用一致性Hash算法计算出尽量稳定的分片顺序,即使注册机器存在波动也不会引起分批分片顺序大的波动;目前采用IP自然排序,可以满足需求,待定;

+ 28 - 0
xxl-job-admin/pom.xml 查看文件

@@ -18,6 +18,34 @@
18 18
 				<type>pom</type>
19 19
 				<scope>import</scope>
20 20
 			</dependency>
21
+
22
+			<!-- jetty -->
23
+			<dependency>
24
+				<groupId>org.eclipse.jetty</groupId>
25
+				<artifactId>jetty-server</artifactId>
26
+				<version>${jetty-server.version}</version>
27
+			</dependency>
28
+			<dependency>
29
+				<groupId>org.eclipse.jetty</groupId>
30
+				<artifactId>jetty-util</artifactId>
31
+				<version>${jetty-server.version}</version>
32
+			</dependency>
33
+			<dependency>
34
+				<groupId>org.eclipse.jetty</groupId>
35
+				<artifactId>jetty-http</artifactId>
36
+				<version>${jetty-server.version}</version>
37
+			</dependency>
38
+			<dependency>
39
+				<groupId>org.eclipse.jetty</groupId>
40
+				<artifactId>jetty-io</artifactId>
41
+				<version>${jetty-server.version}</version>
42
+			</dependency>
43
+			<dependency>
44
+				<groupId>org.eclipse.jetty</groupId>
45
+				<artifactId>jetty-client</artifactId>
46
+				<version>${jetty-server.version}</version>
47
+			</dependency>
48
+
21 49
 		</dependencies>
22 50
 	</dependencyManagement>
23 51
 

+ 9 - 44
xxl-job-admin/src/main/java/com/xxl/job/admin/controller/JobApiController.java 查看文件

@@ -1,69 +1,34 @@
1 1
 package com.xxl.job.admin.controller;
2 2
 
3 3
 import com.xxl.job.admin.controller.annotation.PermessionLimit;
4
+import com.xxl.job.admin.core.schedule.XxlJobDynamicScheduler;
4 5
 import com.xxl.job.core.biz.AdminBiz;
5
-import com.xxl.job.core.rpc.codec.RpcRequest;
6
-import com.xxl.job.core.rpc.codec.RpcResponse;
7
-import com.xxl.job.core.rpc.netcom.NetComServerFactory;
8
-import com.xxl.job.core.rpc.serialize.HessianSerializer;
9
-import com.xxl.job.core.util.HttpClientUtil;
10
-import org.slf4j.Logger;
11
-import org.slf4j.LoggerFactory;
6
+import org.springframework.beans.factory.InitializingBean;
12 7
 import org.springframework.stereotype.Controller;
13 8
 import org.springframework.web.bind.annotation.RequestMapping;
14 9
 
10
+import javax.servlet.ServletException;
15 11
 import javax.servlet.http.HttpServletRequest;
16 12
 import javax.servlet.http.HttpServletResponse;
17 13
 import java.io.IOException;
18
-import java.io.OutputStream;
19 14
 
20 15
 /**
21 16
  * Created by xuxueli on 17/5/10.
22 17
  */
23 18
 @Controller
24
-public class JobApiController {
25
-    private static Logger logger = LoggerFactory.getLogger(JobApiController.class);
19
+public class JobApiController implements InitializingBean {
26 20
 
27
-    private RpcResponse doInvoke(HttpServletRequest request) {
28
-        try {
29
-            // deserialize request
30
-            byte[] requestBytes = HttpClientUtil.readBytes(request);
31
-            if (requestBytes == null || requestBytes.length==0) {
32
-                RpcResponse rpcResponse = new RpcResponse();
33
-                rpcResponse.setError("RpcRequest byte[] is null");
34
-                return rpcResponse;
35
-            }
36
-            RpcRequest rpcRequest = (RpcRequest) HessianSerializer.deserialize(requestBytes, RpcRequest.class);
37 21
 
38
-            // invoke
39
-            RpcResponse rpcResponse = NetComServerFactory.invokeService(rpcRequest, null);
40
-            return rpcResponse;
41
-        } catch (Exception e) {
42
-            logger.error(e.getMessage(), e);
22
+    @Override
23
+    public void afterPropertiesSet() throws Exception {
43 24
 
44
-            RpcResponse rpcResponse = new RpcResponse();
45
-            rpcResponse.setError("Server-error:" + e.getMessage());
46
-            return rpcResponse;
47
-        }
48 25
     }
49 26
 
50 27
     @RequestMapping(AdminBiz.MAPPING)
51 28
     @PermessionLimit(limit=false)
52
-    public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {
53
-
54
-        // invoke
55
-        RpcResponse rpcResponse = doInvoke(request);
56
-
57
-        // serialize response
58
-        byte[] responseBytes = HessianSerializer.serialize(rpcResponse);
59
-
60
-        response.setContentType("text/html;charset=utf-8");
61
-        response.setStatus(HttpServletResponse.SC_OK);
62
-        //baseRequest.setHandled(true);
63
-
64
-        OutputStream out = response.getOutputStream();
65
-        out.write(responseBytes);
66
-        out.flush();
29
+    public void api(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
30
+        XxlJobDynamicScheduler.invokeAdminService(request, response);
67 31
     }
68 32
 
33
+
69 34
 }

+ 3 - 3
xxl-job-admin/src/main/java/com/xxl/job/admin/controller/interceptor/PermissionInterceptor.java 查看文件

@@ -3,8 +3,8 @@ package com.xxl.job.admin.controller.interceptor;
3 3
 import com.xxl.job.admin.controller.annotation.PermessionLimit;
4 4
 import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
5 5
 import com.xxl.job.admin.core.util.CookieUtil;
6
-import org.apache.commons.codec.digest.DigestUtils;
7 6
 import org.springframework.stereotype.Component;
7
+import org.springframework.util.DigestUtils;
8 8
 import org.springframework.web.method.HandlerMethod;
9 9
 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
10 10
 
@@ -29,7 +29,7 @@ public class PermissionInterceptor extends HandlerInterceptorAdapter {
29 29
 			String password = XxlJobAdminConfig.getAdminConfig().getLoginPassword();
30 30
 
31 31
 			// login token
32
-			String tokenTmp = DigestUtils.md5Hex(username + "_" + password);
32
+			String tokenTmp = DigestUtils.md5DigestAsHex(String.valueOf(username + "_" + password).getBytes());		//.getBytes("UTF-8")
33 33
 			tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);
34 34
 
35 35
 			LOGIN_IDENTITY_TOKEN = tokenTmp;
@@ -40,7 +40,7 @@ public class PermissionInterceptor extends HandlerInterceptorAdapter {
40 40
 	public static boolean login(HttpServletResponse response, String username, String password, boolean ifRemember){
41 41
 
42 42
     	// login token
43
-		String tokenTmp = DigestUtils.md5Hex(username + "_" + password);
43
+		String tokenTmp = DigestUtils.md5DigestAsHex(String.valueOf(username + "_" + password).getBytes());
44 44
 		tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);
45 45
 
46 46
 		if (!getLoginIdentityToken().equals(tokenTmp)){

+ 56 - 27
xxl-job-admin/src/main/java/com/xxl/job/admin/core/schedule/XxlJobDynamicScheduler.java 查看文件

@@ -7,27 +7,28 @@ import com.xxl.job.admin.core.thread.JobFailMonitorHelper;
7 7
 import com.xxl.job.admin.core.thread.JobRegistryMonitorHelper;
8 8
 import com.xxl.job.admin.core.thread.JobTriggerPoolHelper;
9 9
 import com.xxl.job.admin.core.util.I18nUtil;
10
-import com.xxl.job.admin.dao.XxlJobGroupDao;
11
-import com.xxl.job.admin.dao.XxlJobInfoDao;
12
-import com.xxl.job.admin.dao.XxlJobLogDao;
13
-import com.xxl.job.admin.dao.XxlJobRegistryDao;
14 10
 import com.xxl.job.core.biz.AdminBiz;
15 11
 import com.xxl.job.core.biz.ExecutorBiz;
16 12
 import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
17
-import com.xxl.job.core.rpc.netcom.NetComClientProxy;
18
-import com.xxl.job.core.rpc.netcom.NetComServerFactory;
13
+import com.xxl.rpc.remoting.invoker.XxlRpcInvokerFactory;
14
+import com.xxl.rpc.remoting.invoker.call.CallType;
15
+import com.xxl.rpc.remoting.invoker.reference.XxlRpcReferenceBean;
16
+import com.xxl.rpc.remoting.net.NetEnum;
17
+import com.xxl.rpc.remoting.net.impl.jetty.server.JettyServerHandler;
18
+import com.xxl.rpc.remoting.provider.XxlRpcProviderFactory;
19
+import com.xxl.rpc.serialize.Serializer;
20
+import org.eclipse.jetty.server.Request;
19 21
 import org.quartz.*;
20 22
 import org.quartz.Trigger.TriggerState;
21 23
 import org.quartz.impl.triggers.CronTriggerImpl;
22 24
 import org.slf4j.Logger;
23 25
 import org.slf4j.LoggerFactory;
24
-import org.springframework.beans.BeansException;
25
-import org.springframework.beans.factory.DisposableBean;
26
-import org.springframework.beans.factory.InitializingBean;
27
-import org.springframework.context.ApplicationContext;
28
-import org.springframework.context.ApplicationContextAware;
29 26
 import org.springframework.util.Assert;
30 27
 
28
+import javax.servlet.ServletException;
29
+import javax.servlet.http.HttpServletRequest;
30
+import javax.servlet.http.HttpServletResponse;
31
+import java.io.IOException;
31 32
 import java.util.Date;
32 33
 import java.util.HashSet;
33 34
 import java.util.concurrent.ConcurrentHashMap;
@@ -50,32 +51,26 @@ public final class XxlJobDynamicScheduler {
50 51
 
51 52
     // ---------------------- init + destroy ----------------------
52 53
     public void start() throws Exception {
54
+        // valid
55
+        Assert.notNull(scheduler, "quartz scheduler is null");
56
+
57
+        // init i18n
58
+        initI18n();
59
+
53 60
         // admin registry monitor run
54 61
         JobRegistryMonitorHelper.getInstance().start();
55 62
 
56 63
         // admin monitor run
57 64
         JobFailMonitorHelper.getInstance().start();
58 65
 
59
-        // admin-server(spring-mvc)
60
-        NetComServerFactory.putService(AdminBiz.class, XxlJobAdminConfig.getAdminConfig().getAdminBiz());
61
-        NetComServerFactory.setAccessToken(XxlJobAdminConfig.getAdminConfig().getAccessToken());
62
-
63
-        // init i18n
64
-        initI18n();
66
+        // admin-server
67
+        initRpcProvider();
65 68
 
66
-        // valid
67
-        Assert.notNull(scheduler, "quartz scheduler is null");
68 69
         logger.info(">>>>>>>>> init xxl-job admin success.");
69 70
     }
70 71
 
71
-    private void initI18n(){
72
-        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
73
-            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
74
-        }
75
-    }
76
-
77
-    public void destroy(){
78 72
 
73
+    public void destroy() throws Exception {
79 74
         // admin trigger pool stop
80 75
         JobTriggerPoolHelper.toStop();
81 76
 
@@ -84,6 +79,38 @@ public final class XxlJobDynamicScheduler {
84 79
 
85 80
         // admin monitor stop
86 81
         JobFailMonitorHelper.getInstance().toStop();
82
+
83
+        // admin-server
84
+        stopRpcProvider();
85
+    }
86
+
87
+
88
+    // ---------------------- I18n ----------------------
89
+
90
+    private void initI18n(){
91
+        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
92
+            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
93
+        }
94
+    }
95
+
96
+    // ---------------------- admin rpc provider (no server version) ----------------------
97
+    private static JettyServerHandler jettyServerHandler;
98
+    private void initRpcProvider(){
99
+        // init
100
+        XxlRpcProviderFactory xxlRpcProviderFactory = new XxlRpcProviderFactory();
101
+        xxlRpcProviderFactory.initConfig(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), null, 0, XxlJobAdminConfig.getAdminConfig().getAccessToken(), null, null);
102
+
103
+        // add services
104
+        xxlRpcProviderFactory.addService(AdminBiz.class.getName(), null, XxlJobAdminConfig.getAdminConfig().getAdminBiz());
105
+
106
+        // jetty handler
107
+        jettyServerHandler = new JettyServerHandler(xxlRpcProviderFactory);
108
+    }
109
+    private void stopRpcProvider() throws Exception {
110
+        new XxlRpcInvokerFactory().stop();
111
+    }
112
+    public static void invokeAdminService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
113
+        jettyServerHandler.handle(null, new Request(null, null), request, response);
87 114
     }
88 115
 
89 116
 
@@ -103,7 +130,9 @@ public final class XxlJobDynamicScheduler {
103 130
         }
104 131
 
105 132
         // set-cache
106
-        executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, address, XxlJobAdminConfig.getAdminConfig().getAccessToken()).getObject();
133
+        executorBiz = (ExecutorBiz) new XxlRpcReferenceBean(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), CallType.SYNC,
134
+                ExecutorBiz.class, null, 10000, address, XxlJobAdminConfig.getAdminConfig().getAccessToken(), null).getObject();
135
+
107 136
         executorBizRepository.put(address, executorBiz);
108 137
         return executorBiz;
109 138
     }

+ 1 - 1
xxl-job-admin/src/main/java/com/xxl/job/admin/core/trigger/XxlJobTrigger.java 查看文件

@@ -12,7 +12,7 @@ import com.xxl.job.core.biz.ExecutorBiz;
12 12
 import com.xxl.job.core.biz.model.ReturnT;
13 13
 import com.xxl.job.core.biz.model.TriggerParam;
14 14
 import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
15
-import com.xxl.job.core.util.IpUtil;
15
+import com.xxl.rpc.util.IpUtil;
16 16
 import org.apache.commons.collections4.CollectionUtils;
17 17
 import org.apache.commons.lang3.StringUtils;
18 18
 import org.slf4j.Logger;

+ 1 - 1
xxl-job-admin/src/main/resources/application.properties 查看文件

@@ -16,7 +16,7 @@ spring.freemarker.request-context-attribute=request
16 16
 mybatis.mapper-locations=classpath:/mybatis-mapper/*Mapper.xml
17 17
 
18 18
 ### xxl-job, datasource
19
-spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl-job?Unicode=true&characterEncoding=UTF-8
19
+spring.datasource.url=jdbc:mysql://192.168.99.100:3306/xxl-job?Unicode=true&characterEncoding=UTF-8
20 20
 spring.datasource.username=root
21 21
 spring.datasource.password=root_pwd
22 22
 spring.datasource.driver-class-name=com.mysql.jdbc.Driver

+ 10 - 3
xxl-job-admin/src/test/java/com/xxl/job/adminbiz/AdminBizTest.java 查看文件

@@ -4,7 +4,10 @@ import com.xxl.job.core.biz.AdminBiz;
4 4
 import com.xxl.job.core.biz.model.RegistryParam;
5 5
 import com.xxl.job.core.biz.model.ReturnT;
6 6
 import com.xxl.job.core.enums.RegistryConfig;
7
-import com.xxl.job.core.rpc.netcom.NetComClientProxy;
7
+import com.xxl.rpc.remoting.invoker.call.CallType;
8
+import com.xxl.rpc.remoting.invoker.reference.XxlRpcReferenceBean;
9
+import com.xxl.rpc.remoting.net.NetEnum;
10
+import com.xxl.rpc.serialize.Serializer;
8 11
 import org.junit.Assert;
9 12
 import org.junit.Test;
10 13
 
@@ -26,7 +29,9 @@ public class AdminBizTest {
26 29
      */
27 30
     @Test
28 31
     public void registryTest() throws Exception {
29
-        AdminBiz adminBiz = (AdminBiz) new NetComClientProxy(AdminBiz.class, addressUrl, accessToken).getObject();
32
+        addressUrl = addressUrl.replace("http://", "");
33
+        AdminBiz adminBiz = (AdminBiz) new XxlRpcReferenceBean(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), CallType.SYNC,
34
+                AdminBiz.class, null, 10000, addressUrl, accessToken, null).getObject();
30 35
 
31 36
         // test executor registry
32 37
         RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), "xxl-job-executor-example", "127.0.0.1:9999");
@@ -41,7 +46,9 @@ public class AdminBizTest {
41 46
      */
42 47
     @Test
43 48
     public void registryRemove() throws Exception {
44
-        AdminBiz adminBiz = (AdminBiz) new NetComClientProxy(AdminBiz.class, addressUrl, accessToken).getObject();
49
+        addressUrl = addressUrl.replace("http://", "");
50
+        AdminBiz adminBiz = (AdminBiz) new XxlRpcReferenceBean(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), CallType.SYNC,
51
+                AdminBiz.class, null, 10000, addressUrl, accessToken, null).getObject();
45 52
 
46 53
         // test executor registry remove
47 54
         RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), "xxl-job-executor-example", "127.0.0.1:9999");

+ 4 - 25
xxl-job-core/pom.xml 查看文件

@@ -15,32 +15,11 @@
15 15
 
16 16
 	<dependencies>
17 17
 
18
-		<!-- slf4j -->
18
+		<!-- xxl-rpc-core -->
19 19
 		<dependency>
20
-			<groupId>org.slf4j</groupId>
21
-			<artifactId>slf4j-api</artifactId>
22
-			<version>${slf4j-api.version}</version>
23
-		</dependency>
24
-
25
-		<!-- jetty -->
26
-		<dependency>
27
-			<groupId>org.eclipse.jetty</groupId>
28
-			<artifactId>jetty-server</artifactId>
29
-			<version>${jetty-server.version}</version>
30
-		</dependency>
31
-
32
-		<!-- httpclient -->
33
-		<dependency>
34
-			<groupId>org.apache.httpcomponents</groupId>
35
-			<artifactId>httpclient</artifactId>
36
-			<version>${httpclient.version}</version>
37
-		</dependency>
38
-
39
-		<!-- hessian -->
40
-		<dependency>
41
-			<groupId>com.caucho</groupId>
42
-			<artifactId>hessian</artifactId>
43
-			<version>${hessian.version}</version>
20
+			<groupId>com.xuxueli</groupId>
21
+			<artifactId>xxl-rpc-core</artifactId>
22
+			<version>1.2.0</version>
44 23
 		</dependency>
45 24
 
46 25
 		<!-- groovy-all -->

+ 94 - 27
xxl-job-core/src/main/java/com/xxl/job/core/executor/XxlJobExecutor.java 查看文件

@@ -6,11 +6,19 @@ import com.xxl.job.core.biz.impl.ExecutorBizImpl;
6 6
 import com.xxl.job.core.handler.IJobHandler;
7 7
 import com.xxl.job.core.handler.annotation.JobHandler;
8 8
 import com.xxl.job.core.log.XxlJobFileAppender;
9
-import com.xxl.job.core.rpc.netcom.NetComClientProxy;
10
-import com.xxl.job.core.rpc.netcom.NetComServerFactory;
9
+import com.xxl.job.core.thread.ExecutorRegistryThread;
11 10
 import com.xxl.job.core.thread.JobLogFileCleanThread;
12 11
 import com.xxl.job.core.thread.JobThread;
13
-import com.xxl.job.core.util.NetUtil;
12
+import com.xxl.job.core.thread.TriggerCallbackThread;
13
+import com.xxl.rpc.registry.impl.LocalServiceRegistry;
14
+import com.xxl.rpc.remoting.invoker.XxlRpcInvokerFactory;
15
+import com.xxl.rpc.remoting.invoker.call.CallType;
16
+import com.xxl.rpc.remoting.invoker.reference.XxlRpcReferenceBean;
17
+import com.xxl.rpc.remoting.net.NetEnum;
18
+import com.xxl.rpc.remoting.provider.XxlRpcProviderFactory;
19
+import com.xxl.rpc.serialize.Serializer;
20
+import com.xxl.rpc.util.IpUtil;
21
+import com.xxl.rpc.util.NetUtil;
14 22
 import org.slf4j.Logger;
15 23
 import org.slf4j.LoggerFactory;
16 24
 import org.springframework.beans.BeansException;
@@ -30,7 +38,7 @@ public class XxlJobExecutor implements ApplicationContextAware {
30 38
 
31 39
     // ---------------------- param ----------------------
32 40
     private String adminAddresses;
33
-    private String appName;
41
+    private static String appName;
34 42
     private String ip;
35 43
     private int port;
36 44
     private String accessToken;
@@ -72,20 +80,26 @@ public class XxlJobExecutor implements ApplicationContextAware {
72 80
 
73 81
     // ---------------------- start + stop ----------------------
74 82
     public void start() throws Exception {
75
-        // init admin-client
76
-        initAdminBizList(adminAddresses, accessToken);
77
-
78
-        // init executor-jobHandlerRepository
79
-        initJobHandlerRepository(applicationContext);
80 83
 
81 84
         // init logpath
82 85
         XxlJobFileAppender.initLogPath(logPath);
83 86
 
84
-        // init executor-server
85
-        initExecutorServer(port, ip, appName, accessToken);
87
+        // init JobHandler Repository
88
+        initJobHandlerRepository(applicationContext);
89
+
90
+        // init admin-client
91
+        initAdminBizList(adminAddresses, accessToken);
86 92
 
87 93
         // init JobLogFileCleanThread
88 94
         JobLogFileCleanThread.getInstance().start(logRetentionDays);
95
+
96
+        // init TriggerCallbackThread
97
+        TriggerCallbackThread.getInstance().start();
98
+
99
+        // init executor-server
100
+        port = port>0?port: NetUtil.findAvailablePort(9999);
101
+        ip = (ip!=null&&ip.trim().length()>0)?ip: IpUtil.getIp();
102
+        initRpcProvider(ip, port, appName, accessToken);
89 103
     }
90 104
     public void destroy(){
91 105
         // destory jobThreadRepository
@@ -96,22 +110,35 @@ public class XxlJobExecutor implements ApplicationContextAware {
96 110
             jobThreadRepository.clear();
97 111
         }
98 112
 
99
-        // destory executor-server
100
-        stopExecutorServer();
101
-
102 113
         // destory JobLogFileCleanThread
103 114
         JobLogFileCleanThread.getInstance().toStop();
115
+
116
+        // destory TriggerCallbackThread
117
+        TriggerCallbackThread.getInstance().toStop();
118
+
119
+        // destory executor-server
120
+        stopRpcProvider();
104 121
     }
105 122
 
106 123
 
107
-    // ---------------------- admin-client ----------------------
124
+    // ---------------------- admin-client (rpc invoker) ----------------------
108 125
     private static List<AdminBiz> adminBizList;
109 126
     private static void initAdminBizList(String adminAddresses, String accessToken) throws Exception {
110 127
         if (adminAddresses!=null && adminAddresses.trim().length()>0) {
111 128
             for (String address: adminAddresses.trim().split(",")) {
112 129
                 if (address!=null && address.trim().length()>0) {
130
+
113 131
                     String addressUrl = address.concat(AdminBiz.MAPPING);
114
-                    AdminBiz adminBiz = (AdminBiz) new NetComClientProxy(AdminBiz.class, addressUrl, accessToken).getObject();
132
+                    if (addressUrl.startsWith("http://")) {
133
+                        addressUrl = addressUrl.replace("http://", "");
134
+                    }
135
+                    if (addressUrl.startsWith("https://")) {
136
+                        addressUrl = addressUrl.replace("https://", "");
137
+                    }
138
+
139
+                    AdminBiz adminBiz = (AdminBiz) new XxlRpcReferenceBean(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), CallType.SYNC,
140
+                            AdminBiz.class, null, 10000, addressUrl, accessToken, null).getObject();
141
+
115 142
                     if (adminBizList == null) {
116 143
                         adminBizList = new ArrayList<AdminBiz>();
117 144
                     }
@@ -125,19 +152,59 @@ public class XxlJobExecutor implements ApplicationContextAware {
125 152
     }
126 153
 
127 154
 
128
-    // ---------------------- executor-server(jetty) ----------------------
129
-    private NetComServerFactory serverFactory = new NetComServerFactory();
130
-    private void initExecutorServer(int port, String ip, String appName, String accessToken) throws Exception {
131
-        // valid param
132
-        port = port>0?port: NetUtil.findAvailablePort(9999);
155
+    // ---------------------- executor-server (rpc provider) ----------------------
156
+    private XxlRpcInvokerFactory xxlRpcInvokerFactory = null;
157
+    private XxlRpcProviderFactory xxlRpcProviderFactory = null;
158
+    private void initRpcProvider(String ip, int port, String appName, String accessToken) throws Exception {
159
+        // init invoker factory
160
+        xxlRpcInvokerFactory = new XxlRpcInvokerFactory();
161
+
162
+        // init, provider factory
163
+        xxlRpcProviderFactory = new XxlRpcProviderFactory();
164
+        xxlRpcProviderFactory.initConfig(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), ip, port, accessToken, ExecutorServiceRegistry.class, null);
165
+
166
+        // add services
167
+        xxlRpcProviderFactory.addService(ExecutorBiz.class.getName(), null, new ExecutorBizImpl());
168
+
169
+        // start
170
+       xxlRpcProviderFactory.start();
133 171
 
134
-        // start server
135
-        NetComServerFactory.putService(ExecutorBiz.class, new ExecutorBizImpl());   // rpc-service, base on jetty
136
-        NetComServerFactory.setAccessToken(accessToken);
137
-        serverFactory.start(port, ip, appName); // jetty + registry
138 172
     }
139
-    private void stopExecutorServer() {
140
-        serverFactory.destroy();    // jetty + registry + callback
173
+
174
+    public static class ExecutorServiceRegistry extends LocalServiceRegistry {
175
+        @Override
176
+        public boolean registry(String key, String value) {
177
+
178
+            // start registry
179
+            if (ExecutorBiz.class.getName().equalsIgnoreCase(key)) {
180
+                ExecutorRegistryThread.getInstance().start(appName, value);
181
+            }
182
+
183
+            return super.registry(key, value);
184
+        }
185
+
186
+        @Override
187
+        public void stop() {
188
+            // stop registry
189
+            ExecutorRegistryThread.getInstance().toStop();
190
+
191
+            super.stop();
192
+        }
193
+    }
194
+
195
+    private void stopRpcProvider() {
196
+        // stop invoker factory
197
+        try {
198
+            xxlRpcInvokerFactory.stop();
199
+        } catch (Exception e) {
200
+            logger.error(e.getMessage(), e);
201
+        }
202
+        // stop provider factory
203
+        try {
204
+            xxlRpcProviderFactory.stop();
205
+        } catch (Exception e) {
206
+            logger.error(e.getMessage(), e);
207
+        }
141 208
     }
142 209
 
143 210
 

+ 0 - 92
xxl-job-core/src/main/java/com/xxl/job/core/rpc/codec/RpcRequest.java 查看文件

@@ -1,92 +0,0 @@
1
-package com.xxl.job.core.rpc.codec;
2
-
3
-import java.io.Serializable;
4
-import java.util.Arrays;
5
-
6
-/**
7
- * request
8
- * @author xuxueli 2015-10-29 19:39:12
9
- */
10
-public class RpcRequest implements Serializable{
11
-	private static final long serialVersionUID = 1L;
12
-	
13
-	private String serverAddress;
14
-	private long createMillisTime;
15
-	private String accessToken;
16
-
17
-    private String className;
18
-    private String methodName;
19
-    private Class<?>[] parameterTypes;
20
-    private Object[] parameters;
21
-
22
-
23
-	public String getServerAddress() {
24
-		return serverAddress;
25
-	}
26
-
27
-	public void setServerAddress(String serverAddress) {
28
-		this.serverAddress = serverAddress;
29
-	}
30
-
31
-	public long getCreateMillisTime() {
32
-		return createMillisTime;
33
-	}
34
-
35
-	public void setCreateMillisTime(long createMillisTime) {
36
-		this.createMillisTime = createMillisTime;
37
-	}
38
-
39
-	public String getAccessToken() {
40
-		return accessToken;
41
-	}
42
-
43
-	public void setAccessToken(String accessToken) {
44
-		this.accessToken = accessToken;
45
-	}
46
-
47
-	public String getClassName() {
48
-		return className;
49
-	}
50
-
51
-	public void setClassName(String className) {
52
-		this.className = className;
53
-	}
54
-
55
-	public String getMethodName() {
56
-		return methodName;
57
-	}
58
-
59
-	public void setMethodName(String methodName) {
60
-		this.methodName = methodName;
61
-	}
62
-
63
-	public Class<?>[] getParameterTypes() {
64
-		return parameterTypes;
65
-	}
66
-
67
-	public void setParameterTypes(Class<?>[] parameterTypes) {
68
-		this.parameterTypes = parameterTypes;
69
-	}
70
-
71
-	public Object[] getParameters() {
72
-		return parameters;
73
-	}
74
-
75
-	public void setParameters(Object[] parameters) {
76
-		this.parameters = parameters;
77
-	}
78
-
79
-	@Override
80
-	public String toString() {
81
-		return "RpcRequest{" +
82
-				"serverAddress='" + serverAddress + '\'' +
83
-				", createMillisTime=" + createMillisTime +
84
-				", accessToken='" + accessToken + '\'' +
85
-				", className='" + className + '\'' +
86
-				", methodName='" + methodName + '\'' +
87
-				", parameterTypes=" + Arrays.toString(parameterTypes) +
88
-				", parameters=" + Arrays.toString(parameters) +
89
-				'}';
90
-	}
91
-
92
-}

+ 0 - 41
xxl-job-core/src/main/java/com/xxl/job/core/rpc/codec/RpcResponse.java 查看文件

@@ -1,41 +0,0 @@
1
-package com.xxl.job.core.rpc.codec;
2
-
3
-import java.io.Serializable;
4
-
5
-/**
6
- * response
7
- * @author xuxueli 2015-10-29 19:39:54
8
- */
9
-public class RpcResponse implements Serializable{
10
-	private static final long serialVersionUID = 1L;
11
-	
12
-    private String error;
13
-    private Object result;
14
-
15
-    public boolean isError() {
16
-        return error != null;
17
-    }
18
-
19
-    public String getError() {
20
-        return error;
21
-    }
22
-
23
-    public void setError(String error) {
24
-        this.error = error;
25
-    }
26
-
27
-    public Object getResult() {
28
-        return result;
29
-    }
30
-
31
-    public void setResult(Object result) {
32
-        this.result = result;
33
-    }
34
-
35
-	@Override
36
-	public String toString() {
37
-		return "NettyResponse [error=" + error
38
-				+ ", result=" + result + "]";
39
-	}
40
-
41
-}

+ 0 - 81
xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/NetComClientProxy.java 查看文件

@@ -1,81 +0,0 @@
1
-package com.xxl.job.core.rpc.netcom;
2
-
3
-import com.xxl.job.core.rpc.codec.RpcRequest;
4
-import com.xxl.job.core.rpc.codec.RpcResponse;
5
-import com.xxl.job.core.rpc.netcom.jetty.client.JettyClient;
6
-import org.slf4j.Logger;
7
-import org.slf4j.LoggerFactory;
8
-import org.springframework.beans.factory.FactoryBean;
9
-
10
-import java.lang.reflect.InvocationHandler;
11
-import java.lang.reflect.Method;
12
-import java.lang.reflect.Proxy;
13
-
14
-/**
15
- * rpc proxy
16
- * @author xuxueli 2015-10-29 20:18:32
17
- */
18
-public class NetComClientProxy implements FactoryBean<Object> {
19
-	private static final Logger logger = LoggerFactory.getLogger(NetComClientProxy.class);
20
-
21
-	// ---------------------- config ----------------------
22
-	private Class<?> iface;
23
-	private String serverAddress;
24
-	private String accessToken;
25
-	private JettyClient client = new JettyClient();
26
-	public NetComClientProxy(Class<?> iface, String serverAddress, String accessToken) {
27
-		this.iface = iface;
28
-		this.serverAddress = serverAddress;
29
-		this.accessToken = accessToken;
30
-	}
31
-
32
-	@Override
33
-	public Object getObject() throws Exception {
34
-		return Proxy.newProxyInstance(Thread.currentThread()
35
-				.getContextClassLoader(), new Class[] { iface },
36
-				new InvocationHandler() {
37
-					@Override
38
-					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
39
-
40
-						// filter method like "Object.toString()"
41
-						if (Object.class.getName().equals(method.getDeclaringClass().getName())) {
42
-							logger.error(">>>>>>>>>>> xxl-rpc proxy class-method not support [{}.{}]", method.getDeclaringClass().getName(), method.getName());
43
-							throw new RuntimeException("xxl-rpc proxy class-method not support");
44
-						}
45
-						
46
-						// request
47
-						RpcRequest request = new RpcRequest();
48
-	                    request.setServerAddress(serverAddress);
49
-	                    request.setCreateMillisTime(System.currentTimeMillis());
50
-	                    request.setAccessToken(accessToken);
51
-	                    request.setClassName(method.getDeclaringClass().getName());
52
-	                    request.setMethodName(method.getName());
53
-	                    request.setParameterTypes(method.getParameterTypes());
54
-	                    request.setParameters(args);
55
-
56
-	                    // send
57
-	                    RpcResponse response = client.send(request);
58
-	                    
59
-	                    // valid response
60
-						if (response == null) {
61
-							throw new Exception("Network request fail, response not found.");
62
-						}
63
-	                    if (response.isError()) {
64
-	                        throw new RuntimeException(response.getError());
65
-	                    } else {
66
-	                        return response.getResult();
67
-	                    }
68
-	                   
69
-					}
70
-				});
71
-	}
72
-	@Override
73
-	public Class<?> getObjectType() {
74
-		return iface;
75
-	}
76
-	@Override
77
-	public boolean isSingleton() {
78
-		return false;
79
-	}
80
-
81
-}

+ 0 - 84
xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/NetComServerFactory.java 查看文件

@@ -1,84 +0,0 @@
1
-package com.xxl.job.core.rpc.netcom;
2
-
3
-import com.xxl.job.core.biz.model.ReturnT;
4
-import com.xxl.job.core.rpc.codec.RpcRequest;
5
-import com.xxl.job.core.rpc.codec.RpcResponse;
6
-import com.xxl.job.core.rpc.netcom.jetty.server.JettyServer;
7
-import org.slf4j.Logger;
8
-import org.slf4j.LoggerFactory;
9
-import org.springframework.cglib.reflect.FastClass;
10
-import org.springframework.cglib.reflect.FastMethod;
11
-
12
-import java.util.HashMap;
13
-import java.util.Map;
14
-
15
-/**
16
- * netcom init
17
- * @author xuxueli 2015-10-31 22:54:27
18
- */
19
-public class NetComServerFactory  {
20
-	private static final Logger logger = LoggerFactory.getLogger(NetComServerFactory.class);
21
-
22
-	// ---------------------- server start ----------------------
23
-	JettyServer server = new JettyServer();
24
-	public void start(int port, String ip, String appName) throws Exception {
25
-		server.start(port, ip, appName);
26
-	}
27
-
28
-	// ---------------------- server destroy ----------------------
29
-	public void destroy(){
30
-		server.destroy();
31
-	}
32
-
33
-	// ---------------------- server instance ----------------------
34
-	/**
35
-	 * init local rpc service map
36
-	 */
37
-	private static Map<String, Object> serviceMap = new HashMap<String, Object>();
38
-	private static String accessToken;
39
-	public static void putService(Class<?> iface, Object serviceBean){
40
-		serviceMap.put(iface.getName(), serviceBean);
41
-	}
42
-	public static void setAccessToken(String accessToken) {
43
-		NetComServerFactory.accessToken = accessToken;
44
-	}
45
-	public static RpcResponse invokeService(RpcRequest request, Object serviceBean) {
46
-		if (serviceBean==null) {
47
-			serviceBean = serviceMap.get(request.getClassName());
48
-		}
49
-		if (serviceBean == null) {
50
-			// TODO
51
-		}
52
-
53
-		RpcResponse response = new RpcResponse();
54
-
55
-		if (System.currentTimeMillis() - request.getCreateMillisTime() > 180000) {
56
-			response.setResult(new ReturnT<String>(ReturnT.FAIL_CODE, "The timestamp difference between admin and executor exceeds the limit."));
57
-			return response;
58
-		}
59
-		if (accessToken!=null && accessToken.trim().length()>0 && !accessToken.trim().equals(request.getAccessToken())) {
60
-			response.setResult(new ReturnT<String>(ReturnT.FAIL_CODE, "The access token[" + request.getAccessToken() + "] is wrong."));
61
-			return response;
62
-		}
63
-
64
-		try {
65
-			Class<?> serviceClass = serviceBean.getClass();
66
-			String methodName = request.getMethodName();
67
-			Class<?>[] parameterTypes = request.getParameterTypes();
68
-			Object[] parameters = request.getParameters();
69
-
70
-			FastClass serviceFastClass = FastClass.create(serviceClass);
71
-			FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
72
-
73
-			Object result = serviceFastMethod.invoke(serviceBean, parameters);
74
-
75
-			response.setResult(result);
76
-		} catch (Throwable t) {
77
-			t.printStackTrace();
78
-			response.setError(t.getMessage());
79
-		}
80
-
81
-		return response;
82
-	}
83
-
84
-}

+ 0 - 48
xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/client/JettyClient.java 查看文件

@@ -1,48 +0,0 @@
1
-package com.xxl.job.core.rpc.netcom.jetty.client;
2
-
3
-import com.xxl.job.core.rpc.codec.RpcRequest;
4
-import com.xxl.job.core.rpc.codec.RpcResponse;
5
-import com.xxl.job.core.rpc.serialize.HessianSerializer;
6
-import com.xxl.job.core.util.HttpClientUtil;
7
-import org.slf4j.Logger;
8
-import org.slf4j.LoggerFactory;
9
-
10
-/**
11
- * jetty client
12
- * @author xuxueli 2015-11-24 22:25:15
13
- */
14
-public class JettyClient {
15
-	private static Logger logger = LoggerFactory.getLogger(JettyClient.class);
16
-
17
-	public RpcResponse send(RpcRequest request) throws Exception {
18
-		try {
19
-			// serialize request
20
-			byte[] requestBytes = HessianSerializer.serialize(request);
21
-
22
-			// reqURL
23
-			String reqURL = request.getServerAddress();
24
-			if (reqURL!=null && reqURL.toLowerCase().indexOf("http")==-1) {
25
-				reqURL = "http://" + request.getServerAddress() + "/";	// IP:PORT, need parse to url
26
-			}
27
-
28
-			// remote invoke
29
-			byte[] responseBytes = HttpClientUtil.postRequest(reqURL, requestBytes);
30
-			if (responseBytes == null || responseBytes.length==0) {
31
-				RpcResponse rpcResponse = new RpcResponse();
32
-				rpcResponse.setError("Network request fail, RpcResponse byte[] is null");
33
-				return rpcResponse;
34
-            }
35
-
36
-            // deserialize response
37
-			RpcResponse rpcResponse = (RpcResponse) HessianSerializer.deserialize(responseBytes, RpcResponse.class);
38
-			return rpcResponse;
39
-		} catch (Exception e) {
40
-			logger.error(e.getMessage(), e);
41
-
42
-			RpcResponse rpcResponse = new RpcResponse();
43
-			rpcResponse.setError("Network request error: " + e.getMessage());
44
-			return rpcResponse;
45
-		}
46
-	}
47
-
48
-}

+ 0 - 92
xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/server/JettyServer.java 查看文件

@@ -1,92 +0,0 @@
1
-package com.xxl.job.core.rpc.netcom.jetty.server;
2
-
3
-import com.xxl.job.core.thread.ExecutorRegistryThread;
4
-import com.xxl.job.core.thread.TriggerCallbackThread;
5
-import org.eclipse.jetty.server.Connector;
6
-import org.eclipse.jetty.server.Handler;
7
-import org.eclipse.jetty.server.Server;
8
-import org.eclipse.jetty.server.ServerConnector;
9
-import org.eclipse.jetty.server.handler.HandlerCollection;
10
-import org.eclipse.jetty.util.thread.ExecutorThreadPool;
11
-import org.slf4j.Logger;
12
-import org.slf4j.LoggerFactory;
13
-
14
-/**
15
- * rpc jetty server
16
- * @author xuxueli 2015-11-19 22:29:03
17
- */
18
-public class JettyServer {
19
-	private static final Logger logger = LoggerFactory.getLogger(JettyServer.class);
20
-
21
-	private Server server;
22
-	private Thread thread;
23
-	public void start(final int port, final String ip, final String appName) throws Exception {
24
-		thread = new Thread(new Runnable() {
25
-			@Override
26
-			public void run() {
27
-
28
-				// The Server
29
-				server = new Server(new ExecutorThreadPool(1000));
30
-
31
-				// HTTP connector
32
-				ServerConnector connector = new ServerConnector(server);
33
-				if (ip!=null && ip.trim().length()>0) {
34
-					//connector.setHost(ip);	// The network interface this connector binds to as an IP address or a hostname.  If null or 0.0.0.0, then bind to all interfaces.
35
-				}
36
-				connector.setPort(port);
37
-				server.setConnectors(new Connector[]{connector});
38
-
39
-				// Set a handler
40
-				HandlerCollection handlerc =new HandlerCollection();
41
-				handlerc.setHandlers(new Handler[]{new JettyServerHandler()});
42
-				server.setHandler(handlerc);
43
-
44
-				try {
45
-					// Start server
46
-					server.start();
47
-					logger.info(">>>>>>>>>>> xxl-job jetty server start success at port:{}.", port);
48
-
49
-					// Start Registry-Server
50
-					ExecutorRegistryThread.getInstance().start(port, ip, appName);
51
-
52
-					// Start Callback-Server
53
-					TriggerCallbackThread.getInstance().start();
54
-
55
-					server.join();	// block until thread stopped
56
-					logger.info(">>>>>>>>>>> xxl-rpc server join success, netcon={}, port={}", JettyServer.class.getName(), port);
57
-				} catch (Exception e) {
58
-					logger.error(e.getMessage(), e);
59
-				} finally {
60
-					//destroy();
61
-				}
62
-			}
63
-		});
64
-		thread.setDaemon(true);	// daemon, service jvm, user thread leave >>> daemon leave >>> jvm leave
65
-		thread.start();
66
-	}
67
-
68
-	public void destroy() {
69
-
70
-		// destroy Registry-Server
71
-		ExecutorRegistryThread.getInstance().toStop();
72
-
73
-		// destroy Callback-Server
74
-		TriggerCallbackThread.getInstance().toStop();
75
-
76
-		// destroy server
77
-		if (server != null) {
78
-			try {
79
-				server.stop();
80
-				server.destroy();
81
-			} catch (Exception e) {
82
-				logger.error(e.getMessage(), e);
83
-			}
84
-		}
85
-		if (thread.isAlive()) {
86
-			thread.interrupt();
87
-		}
88
-
89
-		logger.info(">>>>>>>>>>> xxl-rpc server destroy success, netcon={}", JettyServer.class.getName());
90
-	}
91
-
92
-}

+ 0 - 68
xxl-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/server/JettyServerHandler.java 查看文件

@@ -1,68 +0,0 @@
1
-package com.xxl.job.core.rpc.netcom.jetty.server;
2
-
3
-import com.xxl.job.core.rpc.codec.RpcRequest;
4
-import com.xxl.job.core.rpc.codec.RpcResponse;
5
-import com.xxl.job.core.rpc.netcom.NetComServerFactory;
6
-import com.xxl.job.core.rpc.serialize.HessianSerializer;
7
-import com.xxl.job.core.util.HttpClientUtil;
8
-import org.eclipse.jetty.server.Request;
9
-import org.eclipse.jetty.server.handler.AbstractHandler;
10
-import org.slf4j.Logger;
11
-import org.slf4j.LoggerFactory;
12
-
13
-import javax.servlet.ServletException;
14
-import javax.servlet.http.HttpServletRequest;
15
-import javax.servlet.http.HttpServletResponse;
16
-import java.io.IOException;
17
-import java.io.OutputStream;
18
-
19
-/**
20
- * jetty handler
21
- * @author xuxueli 2015-11-19 22:32:36
22
- */
23
-public class JettyServerHandler extends AbstractHandler {
24
-	private static Logger logger = LoggerFactory.getLogger(JettyServerHandler.class);
25
-
26
-	@Override
27
-	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
28
-		
29
-		// invoke
30
-        RpcResponse rpcResponse = doInvoke(request);
31
-
32
-        // serialize response
33
-        byte[] responseBytes = HessianSerializer.serialize(rpcResponse);
34
-		
35
-		response.setContentType("text/html;charset=utf-8");
36
-		response.setStatus(HttpServletResponse.SC_OK);
37
-		baseRequest.setHandled(true);
38
-		
39
-		OutputStream out = response.getOutputStream();
40
-		out.write(responseBytes);
41
-		out.flush();
42
-		
43
-	}
44
-
45
-	private RpcResponse doInvoke(HttpServletRequest request) {
46
-		try {
47
-			// deserialize request
48
-			byte[] requestBytes = HttpClientUtil.readBytes(request);
49
-			if (requestBytes == null || requestBytes.length==0) {
50
-				RpcResponse rpcResponse = new RpcResponse();
51
-				rpcResponse.setError("RpcRequest byte[] is null");
52
-				return rpcResponse;
53
-			}
54
-			RpcRequest rpcRequest = (RpcRequest) HessianSerializer.deserialize(requestBytes, RpcRequest.class);
55
-
56
-			// invoke
57
-			RpcResponse rpcResponse = NetComServerFactory.invokeService(rpcRequest, null);
58
-			return rpcResponse;
59
-		} catch (Exception e) {
60
-			logger.error(e.getMessage(), e);
61
-
62
-			RpcResponse rpcResponse = new RpcResponse();
63
-			rpcResponse.setError("Server-error:" + e.getMessage());
64
-			return rpcResponse;
65
-		}
66
-	}
67
-
68
-}

+ 0 - 62
xxl-job-core/src/main/java/com/xxl/job/core/rpc/serialize/HessianSerializer.java 查看文件

@@ -1,62 +0,0 @@
1
-package com.xxl.job.core.rpc.serialize;
2
-
3
-import com.caucho.hessian.io.Hessian2Input;
4
-import com.caucho.hessian.io.Hessian2Output;
5
-
6
-import java.io.ByteArrayInputStream;
7
-import java.io.ByteArrayOutputStream;
8
-import java.io.IOException;
9
-
10
-/**
11
- * hessian serialize
12
- * @author xuxueli 2015-9-26 02:53:29
13
- */
14
-public class HessianSerializer  {
15
-
16
-	public static <T> byte[] serialize(T obj){
17
-		ByteArrayOutputStream os = new ByteArrayOutputStream();
18
-		Hessian2Output ho = new Hessian2Output(os);
19
-		try {
20
-			ho.writeObject(obj);
21
-			ho.flush();
22
-			byte[] result = os.toByteArray();
23
-			return result;
24
-		} catch (IOException e) {
25
-			throw new IllegalStateException(e.getMessage(), e);
26
-		} finally {
27
-			try {
28
-				ho.close();
29
-			} catch (IOException e) {
30
-				throw new IllegalStateException(e.getMessage(), e);
31
-			}
32
-			try {
33
-				os.close();
34
-			} catch (IOException e) {
35
-				throw new IllegalStateException(e.getMessage(), e);
36
-			}
37
-		}
38
-	}
39
-
40
-	public static <T> Object deserialize(byte[] bytes, Class<T> clazz) {
41
-		ByteArrayInputStream is = new ByteArrayInputStream(bytes);
42
-		Hessian2Input hi = new Hessian2Input(is);
43
-		try {
44
-			Object result = hi.readObject();
45
-			return result;
46
-		} catch (IOException e) {
47
-			throw new IllegalStateException(e.getMessage(), e);
48
-		} finally {
49
-			try {
50
-				hi.close();
51
-			} catch (Exception e) {
52
-				throw new IllegalStateException(e.getMessage(), e);
53
-			}
54
-			try {
55
-				is.close();
56
-			} catch (IOException e) {
57
-				throw new IllegalStateException(e.getMessage(), e);
58
-			}
59
-		}
60
-	}
61
-	
62
-}

+ 3 - 12
xxl-job-core/src/main/java/com/xxl/job/core/thread/ExecutorRegistryThread.java 查看文件

@@ -5,7 +5,6 @@ import com.xxl.job.core.biz.model.RegistryParam;
5 5
 import com.xxl.job.core.biz.model.ReturnT;
6 6
 import com.xxl.job.core.enums.RegistryConfig;
7 7
 import com.xxl.job.core.executor.XxlJobExecutor;
8
-import com.xxl.job.core.util.IpUtil;
9 8
 import org.slf4j.Logger;
10 9
 import org.slf4j.LoggerFactory;
11 10
 
@@ -24,7 +23,7 @@ public class ExecutorRegistryThread extends Thread {
24 23
 
25 24
     private Thread registryThread;
26 25
     private volatile boolean toStop = false;
27
-    public void start(final int port, final String ip, final String appName){
26
+    public void start(final String appName, final String address){
28 27
 
29 28
         // valid
30 29
         if (appName==null || appName.trim().length()==0) {
@@ -36,14 +35,6 @@ public class ExecutorRegistryThread extends Thread {
36 35
             return;
37 36
         }
38 37
 
39
-        // executor address (generate addredd = ip:port)
40
-        final String executorAddress;
41
-        if (ip != null && ip.trim().length()>0) {
42
-            executorAddress = ip.trim().concat(":").concat(String.valueOf(port));
43
-        } else {
44
-            executorAddress = IpUtil.getIpPort(port);
45
-        }
46
-
47 38
         registryThread = new Thread(new Runnable() {
48 39
             @Override
49 40
             public void run() {
@@ -51,7 +42,7 @@ public class ExecutorRegistryThread extends Thread {
51 42
                 // registry
52 43
                 while (!toStop) {
53 44
                     try {
54
-                        RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appName, executorAddress);
45
+                        RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appName, address);
55 46
                         for (AdminBiz adminBiz: XxlJobExecutor.getAdminBizList()) {
56 47
                             try {
57 48
                                 ReturnT<String> registryResult = adminBiz.registry(registryParam);
@@ -80,7 +71,7 @@ public class ExecutorRegistryThread extends Thread {
80 71
 
81 72
                 // registry remove
82 73
                 try {
83
-                    RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appName, executorAddress);
74
+                    RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appName, address);
84 75
                     for (AdminBiz adminBiz: XxlJobExecutor.getAdminBizList()) {
85 76
                         try {
86 77
                             ReturnT<String> registryResult = adminBiz.registryRemove(registryParam);

+ 0 - 110
xxl-job-core/src/main/java/com/xxl/job/core/util/HttpClientUtil.java 查看文件

@@ -1,110 +0,0 @@
1
-package com.xxl.job.core.util;
2
-
3
-import org.apache.http.HttpEntity;
4
-import org.apache.http.HttpResponse;
5
-import org.apache.http.client.config.RequestConfig;
6
-import org.apache.http.client.methods.HttpPost;
7
-import org.apache.http.entity.ByteArrayEntity;
8
-import org.apache.http.entity.ContentType;
9
-import org.apache.http.impl.client.CloseableHttpClient;
10
-import org.apache.http.impl.client.HttpClients;
11
-import org.apache.http.util.EntityUtils;
12
-import org.slf4j.Logger;
13
-import org.slf4j.LoggerFactory;
14
-
15
-import javax.servlet.http.HttpServletRequest;
16
-import java.io.IOException;
17
-import java.io.InputStream;
18
-
19
-/**
20
- * httpclient util
21
- * @author xuxueli 2015-10-31 19:50:41
22
- */
23
-public class HttpClientUtil {
24
-	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
25
-
26
-	/**
27
-	 * post request
28
-	 */
29
-	public static byte[] postRequest(String reqURL, byte[] data) throws Exception {
30
-		byte[] responseBytes = null;
31
-		
32
-		HttpPost httpPost = new HttpPost(reqURL);
33
-		//CloseableHttpClient httpClient = HttpClients.createDefault();
34
-		CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();	// disable retry
35
-
36
-		try {
37
-			// init post
38
-			/*if (params != null && !params.isEmpty()) {
39
-				List<NameValuePair> formParams = new ArrayList<NameValuePair>();
40
-				for (Map.Entry<String, String> entry : params.entrySet()) {
41
-					formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
42
-				}
43
-				httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
44
-			}*/
45
-
46
-			// timeout
47
-			RequestConfig requestConfig = RequestConfig.custom()
48
-                    .setConnectionRequestTimeout(10000)
49
-                    .setSocketTimeout(10000)
50
-                    .setConnectTimeout(10000)
51
-                    .build();
52
-
53
-			httpPost.setConfig(requestConfig);
54
-
55
-			// data
56
-			if (data != null) {
57
-				httpPost.setEntity(new ByteArrayEntity(data, ContentType.DEFAULT_BINARY));
58
-			}
59
-			// do post
60
-			HttpResponse response = httpClient.execute(httpPost);
61
-			HttpEntity entity = response.getEntity();
62
-			if (null != entity) {
63
-				responseBytes = EntityUtils.toByteArray(entity);
64
-				EntityUtils.consume(entity);
65
-			}
66
-		} catch (Exception e) {
67
-			throw e;
68
-		} finally {
69
-			httpPost.releaseConnection();
70
-			try {
71
-				httpClient.close();
72
-			} catch (IOException e) {
73
-				logger.error(e.getMessage(), e);
74
-			}
75
-		}
76
-		return responseBytes;
77
-	}
78
-	
79
-	/**
80
-	 * read bytes from http request
81
-	 * @param request
82
-	 * @return
83
-	 * @throws IOException 
84
-	 */
85
-	public static final byte[] readBytes(HttpServletRequest request) throws IOException {
86
-		request.setCharacterEncoding("UTF-8");
87
-        int contentLen = request.getContentLength();
88
-		InputStream is = request.getInputStream();
89
-		if (contentLen > 0) {
90
-			int readLen = 0;
91
-			int readLengthThisTime = 0;
92
-			byte[] message = new byte[contentLen];
93
-			try {
94
-				while (readLen != contentLen) {
95
-					readLengthThisTime = is.read(message, readLen, contentLen - readLen);
96
-					if (readLengthThisTime == -1) {
97
-						break;
98
-					}
99
-					readLen += readLengthThisTime;
100
-				}
101
-				return message;
102
-			} catch (IOException e) {
103
-				logger.error(e.getMessage(), e);
104
-				throw e;
105
-			}
106
-		}
107
-		return new byte[] {};
108
-	}
109
-
110
-}

+ 0 - 135
xxl-job-core/src/main/java/com/xxl/job/core/util/IpUtil.java 查看文件

@@ -1,135 +0,0 @@
1
-package com.xxl.job.core.util;
2
-
3
-import org.slf4j.Logger;
4
-import org.slf4j.LoggerFactory;
5
-
6
-import java.net.InetAddress;
7
-import java.net.NetworkInterface;
8
-import java.net.UnknownHostException;
9
-import java.util.Enumeration;
10
-import java.util.regex.Pattern;
11
-
12
-/**
13
- * get ip
14
- *
15
- * @author xuxueli 2016-5-22 11:38:05
16
- */
17
-public class IpUtil {
18
-	private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
19
-
20
-	private static final String ANYHOST = "0.0.0.0";
21
-	private static final String LOCALHOST = "127.0.0.1";
22
-	public static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
23
-
24
-	private static volatile String LOCAL_ADDRESS = null;
25
-
26
-	/**
27
-	 * valid address
28
-	 * @param address
29
-	 * @return boolean
30
-	 */
31
-	private static boolean isValidAddress(InetAddress address) {
32
-		if (address == null || address.isLoopbackAddress() || address.isLinkLocalAddress()) {
33
-			return false;
34
-		}
35
-		String name = address.getHostAddress();
36
-		return (name != null
37
-				&& ! ANYHOST.equals(name)
38
-				&& ! LOCALHOST.equals(name)
39
-				&& IP_PATTERN.matcher(name).matches());
40
-	}
41
-
42
-	/**
43
-	 * get first valid addredd
44
-	 *
45
-	 * @return InetAddress
46
-	 */
47
-	private static InetAddress getFirstValidAddress() {
48
-
49
-		// NetworkInterface address
50
-		try {
51
-			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
52
-			if (interfaces != null) {
53
-				while (interfaces.hasMoreElements()) {
54
-					try {
55
-						NetworkInterface network = interfaces.nextElement();
56
-						Enumeration<InetAddress> addresses = network.getInetAddresses();
57
-						if (addresses != null) {
58
-							while (addresses.hasMoreElements()) {
59
-								try {
60
-									InetAddress address = addresses.nextElement();
61
-									if (isValidAddress(address)) {
62
-										return address;
63
-									}
64
-								} catch (Throwable e) {
65
-									logger.error("Failed to retriving ip address, " + e.getMessage(), e);
66
-								}
67
-							}
68
-						}
69
-					} catch (Throwable e) {
70
-						logger.error("Failed to retriving ip address, " + e.getMessage(), e);
71
-					}
72
-				}
73
-			}
74
-		} catch (Throwable e) {
75
-			logger.error("Failed to retriving ip address, " + e.getMessage(), e);
76
-		}
77
-
78
-		// getLocalHost address
79
-		try {
80
-			InetAddress localAddress = InetAddress.getLocalHost();
81
-			if (isValidAddress(localAddress)) {
82
-				return localAddress;
83
-			}
84
-		} catch (Throwable e) {
85
-			logger.error("Failed to retriving ip address, " + e.getMessage(), e);
86
-		}
87
-		
88
-		logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");
89
-		return null;
90
-	}
91
-	
92
-
93
-	/**
94
-	 * get address
95
-	 *
96
-	 * @return String
97
-	 */
98
-	private static String getAddress() {
99
-		if (LOCAL_ADDRESS != null) {
100
-			return LOCAL_ADDRESS;
101
-		}
102
-		InetAddress localAddress = getFirstValidAddress();
103
-		LOCAL_ADDRESS = localAddress.getHostAddress();
104
-		return LOCAL_ADDRESS;
105
-	}
106
-
107
-	/**
108
-	 * get ip
109
-	 *
110
-	 * @return String
111
-	 */
112
-	public static String getIp(){
113
-		return getAddress();
114
-	}
115
-
116
-	/**
117
-	 * get ip:port
118
-	 *
119
-	 * @param port
120
-	 * @return String
121
-	 */
122
-	public static String getIpPort(int port){
123
-		String ip = getIp();
124
-		if (ip==null) {
125
-			return null;
126
-		}
127
-		return ip.concat(":").concat(String.valueOf(port));
128
-	}
129
-
130
-	public static void main(String[] args) throws UnknownHostException {
131
-		System.out.println(getIp());
132
-		System.out.println(getIpPort(8080));
133
-	}
134
-
135
-}

+ 0 - 70
xxl-job-core/src/main/java/com/xxl/job/core/util/NetUtil.java 查看文件

@@ -1,70 +0,0 @@
1
-package com.xxl.job.core.util;
2
-
3
-import org.slf4j.Logger;
4
-import org.slf4j.LoggerFactory;
5
-
6
-import java.io.IOException;
7
-import java.net.ServerSocket;
8
-
9
-/**
10
- * net util
11
- *
12
- * @author xuxueli 2017-11-29 17:00:25
13
- */
14
-public class NetUtil {
15
-    private static Logger logger = LoggerFactory.getLogger(NetUtil.class);
16
-
17
-    /**
18
-     * find avaliable port
19
-     *
20
-     * @param defaultPort
21
-     * @return
22
-     */
23
-    public static int findAvailablePort(int defaultPort) {
24
-        int portTmp = defaultPort;
25
-        while (portTmp < 65535) {
26
-            if (!isPortUsed(portTmp)) {
27
-                return portTmp;
28
-            } else {
29
-                portTmp++;
30
-            }
31
-        }
32
-        portTmp = defaultPort--;
33
-        while (portTmp > 0) {
34
-            if (!isPortUsed(portTmp)) {
35
-                return portTmp;
36
-            } else {
37
-                portTmp--;
38
-            }
39
-        }
40
-        throw new IllegalStateException("no available port.");
41
-    }
42
-
43
-    /**
44
-     * check port used
45
-     *
46
-     * @param port
47
-     * @return
48
-     */
49
-    public static boolean isPortUsed(int port) {
50
-        boolean used = false;
51
-        ServerSocket serverSocket = null;
52
-        try {
53
-            serverSocket = new ServerSocket(port);
54
-            used = false;
55
-        } catch (IOException e) {
56
-            logger.debug(">>>>>>>>>>> xxl-job, port[{}] is in use.", port);
57
-            used = true;
58
-        } finally {
59
-            if (serverSocket != null) {
60
-                try {
61
-                    serverSocket.close();
62
-                } catch (IOException e) {
63
-                    logger.info("");
64
-                }
65
-            }
66
-        }
67
-        return used;
68
-    }
69
-
70
-}

+ 22 - 47
xxl-job-executor-samples/xxl-job-executor-sample-jfinal/src/main/java/com/xuxueli/executor/sample/jfinal/jobhandler/HttpJobHandler.java 查看文件

@@ -3,18 +3,13 @@ package com.xuxueli.executor.sample.jfinal.jobhandler;
3 3
 import com.xxl.job.core.biz.model.ReturnT;
4 4
 import com.xxl.job.core.handler.IJobHandler;
5 5
 import com.xxl.job.core.log.XxlJobLogger;
6
-import com.xxl.job.core.util.ShardingUtil;
7
-import org.apache.http.HttpEntity;
8
-import org.apache.http.HttpResponse;
9
-import org.apache.http.client.config.RequestConfig;
10
-import org.apache.http.client.methods.HttpGet;
11
-import org.apache.http.impl.client.CloseableHttpClient;
12
-import org.apache.http.impl.client.HttpClients;
13
-import org.apache.http.util.EntityUtils;
14
-import org.slf4j.Logger;
15
-import org.slf4j.LoggerFactory;
6
+import org.eclipse.jetty.client.HttpClient;
7
+import org.eclipse.jetty.client.api.ContentResponse;
8
+import org.eclipse.jetty.client.api.Request;
9
+import org.eclipse.jetty.http.HttpMethod;
10
+import org.eclipse.jetty.http.HttpStatus;
16 11
 
17
-import java.io.IOException;
12
+import java.util.concurrent.TimeUnit;
18 13
 
19 14
 /**
20 15
  * 跨平台Http任务
@@ -32,46 +27,26 @@ public class HttpJobHandler extends IJobHandler {
32 27
 			return FAIL;
33 28
 		}
34 29
 
35
-		// httpGet config
36
-		HttpGet httpGet = new HttpGet(param);
37
-		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
38
-		httpGet.setConfig(requestConfig);
30
+		// httpclient
31
+		HttpClient httpClient = new HttpClient();
32
+		httpClient.setFollowRedirects(false);	// Configure HttpClient, for example:
33
+		httpClient.start();						// Start HttpClient
39 34
 
40
-		CloseableHttpClient httpClient = null;
41
-		try{
42
-			httpClient = HttpClients.custom().disableAutomaticRetries().build();
35
+		// request
36
+		Request request = httpClient.newRequest(param);
37
+		request.method(HttpMethod.GET);
38
+		request.timeout(5000, TimeUnit.MILLISECONDS);
43 39
 
44
-			// parse response
45
-			HttpResponse response = httpClient.execute(httpGet);
46
-			HttpEntity entity = response.getEntity();
47
-			if (response.getStatusLine().getStatusCode() != 200) {
48
-				XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatusLine().getStatusCode());
49
-				return FAIL;
50
-			}
51
-			if (null == entity) {
52
-				XxlJobLogger.log("Http Entity Empty.");
53
-				return FAIL;
54
-			}
55
-
56
-			String responseMsg = EntityUtils.toString(entity, "UTF-8");
57
-			XxlJobLogger.log(responseMsg);
58
-			EntityUtils.consume(entity);
59
-			return SUCCESS;
60
-		} catch (Exception e) {
61
-			XxlJobLogger.log(e);
40
+		// invoke
41
+		ContentResponse response = request.send();
42
+		if (response.getStatus() != HttpStatus.OK_200) {
43
+			XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatus());
62 44
 			return FAIL;
63
-		} finally{
64
-			if (httpGet!=null) {
65
-				httpGet.releaseConnection();
66
-			}
67
-			if (httpClient!=null) {
68
-				try {
69
-					httpClient.close();
70
-				} catch (IOException e) {
71
-					XxlJobLogger.log(e);
72
-				}
73
-			}
74 45
 		}
46
+
47
+		String responseMsg = response.getContentAsString();
48
+		XxlJobLogger.log(responseMsg);
49
+		return SUCCESS;
75 50
 	}
76 51
 
77 52
 }

+ 22 - 44
xxl-job-executor-samples/xxl-job-executor-sample-nutz/src/main/java/com/xuxueli/executor/sample/nutz/jobhandler/HttpJobHandler.java 查看文件

@@ -4,16 +4,14 @@ import com.xxl.job.core.biz.model.ReturnT;
4 4
 import com.xxl.job.core.handler.IJobHandler;
5 5
 import com.xxl.job.core.handler.annotation.JobHandler;
6 6
 import com.xxl.job.core.log.XxlJobLogger;
7
-import org.apache.http.HttpEntity;
8
-import org.apache.http.HttpResponse;
9
-import org.apache.http.client.config.RequestConfig;
10
-import org.apache.http.client.methods.HttpGet;
11
-import org.apache.http.impl.client.CloseableHttpClient;
12
-import org.apache.http.impl.client.HttpClients;
13
-import org.apache.http.util.EntityUtils;
7
+import org.eclipse.jetty.client.HttpClient;
8
+import org.eclipse.jetty.client.api.ContentResponse;
9
+import org.eclipse.jetty.client.api.Request;
10
+import org.eclipse.jetty.http.HttpMethod;
11
+import org.eclipse.jetty.http.HttpStatus;
14 12
 import org.nutz.ioc.loader.annotation.IocBean;
15 13
 
16
-import java.io.IOException;
14
+import java.util.concurrent.TimeUnit;
17 15
 
18 16
 /**
19 17
  * 跨平台Http任务
@@ -33,46 +31,26 @@ public class HttpJobHandler extends IJobHandler {
33 31
 			return FAIL;
34 32
 		}
35 33
 
36
-		// httpGet config
37
-		HttpGet httpGet = new HttpGet(param);
38
-		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
39
-		httpGet.setConfig(requestConfig);
34
+		// httpclient
35
+		HttpClient httpClient = new HttpClient();
36
+		httpClient.setFollowRedirects(false);	// Configure HttpClient, for example:
37
+		httpClient.start();						// Start HttpClient
40 38
 
41
-		CloseableHttpClient httpClient = null;
42
-		try{
43
-			httpClient = HttpClients.custom().disableAutomaticRetries().build();
39
+		// request
40
+		Request request = httpClient.newRequest(param);
41
+		request.method(HttpMethod.GET);
42
+		request.timeout(5000, TimeUnit.MILLISECONDS);
44 43
 
45
-			// parse response
46
-			HttpResponse response = httpClient.execute(httpGet);
47
-			HttpEntity entity = response.getEntity();
48
-			if (response.getStatusLine().getStatusCode() != 200) {
49
-				XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatusLine().getStatusCode());
50
-				return FAIL;
51
-			}
52
-			if (null == entity) {
53
-				XxlJobLogger.log("Http Entity Empty.");
54
-				return FAIL;
55
-			}
56
-
57
-			String responseMsg = EntityUtils.toString(entity, "UTF-8");
58
-			XxlJobLogger.log(responseMsg);
59
-			EntityUtils.consume(entity);
60
-			return SUCCESS;
61
-		} catch (Exception e) {
62
-			XxlJobLogger.log(e);
44
+		// invoke
45
+		ContentResponse response = request.send();
46
+		if (response.getStatus() != HttpStatus.OK_200) {
47
+			XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatus());
63 48
 			return FAIL;
64
-		} finally{
65
-			if (httpGet!=null) {
66
-				httpGet.releaseConnection();
67
-			}
68
-			if (httpClient!=null) {
69
-				try {
70
-					httpClient.close();
71
-				} catch (IOException e) {
72
-					XxlJobLogger.log(e);
73
-				}
74
-			}
75 49
 		}
50
+
51
+		String responseMsg = response.getContentAsString();
52
+		XxlJobLogger.log(responseMsg);
53
+		return SUCCESS;
76 54
 	}
77 55
 
78 56
 }

+ 22 - 44
xxl-job-executor-samples/xxl-job-executor-sample-spring/src/main/java/com/xxl/job/executor/service/jobhandler/HttpJobHandler.java 查看文件

@@ -4,16 +4,14 @@ import com.xxl.job.core.biz.model.ReturnT;
4 4
 import com.xxl.job.core.handler.IJobHandler;
5 5
 import com.xxl.job.core.handler.annotation.JobHandler;
6 6
 import com.xxl.job.core.log.XxlJobLogger;
7
-import org.apache.http.HttpEntity;
8
-import org.apache.http.HttpResponse;
9
-import org.apache.http.client.config.RequestConfig;
10
-import org.apache.http.client.methods.HttpGet;
11
-import org.apache.http.impl.client.CloseableHttpClient;
12
-import org.apache.http.impl.client.HttpClients;
13
-import org.apache.http.util.EntityUtils;
7
+import org.eclipse.jetty.client.HttpClient;
8
+import org.eclipse.jetty.client.api.ContentResponse;
9
+import org.eclipse.jetty.client.api.Request;
10
+import org.eclipse.jetty.http.HttpMethod;
11
+import org.eclipse.jetty.http.HttpStatus;
14 12
 import org.springframework.stereotype.Component;
15 13
 
16
-import java.io.IOException;
14
+import java.util.concurrent.TimeUnit;
17 15
 
18 16
 /**
19 17
  * 跨平台Http任务
@@ -33,46 +31,26 @@ public class HttpJobHandler extends IJobHandler {
33 31
 			return FAIL;
34 32
 		}
35 33
 
36
-		// httpGet config
37
-		HttpGet httpGet = new HttpGet(param);
38
-		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
39
-		httpGet.setConfig(requestConfig);
34
+		// httpclient
35
+		HttpClient httpClient = new HttpClient();
36
+		httpClient.setFollowRedirects(false);	// Configure HttpClient, for example:
37
+		httpClient.start();						// Start HttpClient
40 38
 
41
-		CloseableHttpClient httpClient = null;
42
-		try{
43
-			httpClient = HttpClients.custom().disableAutomaticRetries().build();
39
+		// request
40
+		Request request = httpClient.newRequest(param);
41
+		request.method(HttpMethod.GET);
42
+		request.timeout(5000, TimeUnit.MILLISECONDS);
44 43
 
45
-			// parse response
46
-			HttpResponse response = httpClient.execute(httpGet);
47
-			HttpEntity entity = response.getEntity();
48
-			if (response.getStatusLine().getStatusCode() != 200) {
49
-				XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatusLine().getStatusCode());
50
-				return FAIL;
51
-			}
52
-			if (null == entity) {
53
-				XxlJobLogger.log("Http Entity Empty.");
54
-				return FAIL;
55
-			}
56
-
57
-			String responseMsg = EntityUtils.toString(entity, "UTF-8");
58
-			XxlJobLogger.log(responseMsg);
59
-			EntityUtils.consume(entity);
60
-			return SUCCESS;
61
-		} catch (Exception e) {
62
-			XxlJobLogger.log(e);
44
+		// invoke
45
+		ContentResponse response = request.send();
46
+		if (response.getStatus() != HttpStatus.OK_200) {
47
+			XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatus());
63 48
 			return FAIL;
64
-		} finally{
65
-			if (httpGet!=null) {
66
-				httpGet.releaseConnection();
67
-			}
68
-			if (httpClient!=null) {
69
-				try {
70
-					httpClient.close();
71
-				} catch (IOException e) {
72
-					XxlJobLogger.log(e);
73
-				}
74
-			}
75 49
 		}
50
+
51
+		String responseMsg = response.getContentAsString();
52
+		XxlJobLogger.log(responseMsg);
53
+		return SUCCESS;
76 54
 	}
77 55
 
78 56
 }

+ 7 - 2
xxl-job-executor-samples/xxl-job-executor-sample-spring/src/test/java/com/xxl/executor/test/DemoJobHandlerTest.java 查看文件

@@ -5,7 +5,10 @@ import com.xxl.job.core.biz.model.ReturnT;
5 5
 import com.xxl.job.core.biz.model.TriggerParam;
6 6
 import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
7 7
 import com.xxl.job.core.glue.GlueTypeEnum;
8
-import com.xxl.job.core.rpc.netcom.NetComClientProxy;
8
+import com.xxl.rpc.remoting.invoker.call.CallType;
9
+import com.xxl.rpc.remoting.invoker.reference.XxlRpcReferenceBean;
10
+import com.xxl.rpc.remoting.net.NetEnum;
11
+import com.xxl.rpc.serialize.Serializer;
9 12
 
10 13
 /**
11 14
  * executor-api client, test
@@ -34,7 +37,9 @@ public class DemoJobHandlerTest {
34 37
 
35 38
         // do remote trigger
36 39
         String accessToken = null;
37
-        ExecutorBiz executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, "127.0.0.1:9999", null).getObject();
40
+        ExecutorBiz executorBiz = (ExecutorBiz) new XxlRpcReferenceBean(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), CallType.SYNC,
41
+                ExecutorBiz.class, null, 10000, "127.0.0.1:9999", null, null).getObject();
42
+
38 43
         ReturnT<String> runResult = executorBiz.run(triggerParam);
39 44
     }
40 45
 

+ 5 - 0
xxl-job-executor-samples/xxl-job-executor-sample-springboot/pom.xml 查看文件

@@ -53,6 +53,11 @@
53 53
                 <artifactId>jetty-io</artifactId>
54 54
                 <version>${jetty-server.version}</version>
55 55
             </dependency>
56
+            <dependency>
57
+                <groupId>org.eclipse.jetty</groupId>
58
+                <artifactId>jetty-client</artifactId>
59
+                <version>${jetty-server.version}</version>
60
+            </dependency>
56 61
 
57 62
         </dependencies>
58 63
     </dependencyManagement>

+ 22 - 44
xxl-job-executor-samples/xxl-job-executor-sample-springboot/src/main/java/com/xxl/job/executor/service/jobhandler/HttpJobHandler.java 查看文件

@@ -4,16 +4,14 @@ import com.xxl.job.core.biz.model.ReturnT;
4 4
 import com.xxl.job.core.handler.IJobHandler;
5 5
 import com.xxl.job.core.handler.annotation.JobHandler;
6 6
 import com.xxl.job.core.log.XxlJobLogger;
7
-import org.apache.http.HttpEntity;
8
-import org.apache.http.HttpResponse;
9
-import org.apache.http.client.config.RequestConfig;
10
-import org.apache.http.client.methods.HttpGet;
11
-import org.apache.http.impl.client.CloseableHttpClient;
12
-import org.apache.http.impl.client.HttpClients;
13
-import org.apache.http.util.EntityUtils;
7
+import org.eclipse.jetty.client.HttpClient;
8
+import org.eclipse.jetty.client.api.ContentResponse;
9
+import org.eclipse.jetty.client.api.Request;
10
+import org.eclipse.jetty.http.HttpMethod;
11
+import org.eclipse.jetty.http.HttpStatus;
14 12
 import org.springframework.stereotype.Component;
15 13
 
16
-import java.io.IOException;
14
+import java.util.concurrent.TimeUnit;
17 15
 
18 16
 /**
19 17
  * 跨平台Http任务
@@ -33,46 +31,26 @@ public class HttpJobHandler extends IJobHandler {
33 31
 			return FAIL;
34 32
 		}
35 33
 
36
-		// httpGet config
37
-		HttpGet httpGet = new HttpGet(param);
38
-		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
39
-		httpGet.setConfig(requestConfig);
34
+		// httpclient
35
+		HttpClient httpClient = new HttpClient();
36
+		httpClient.setFollowRedirects(false);	// Configure HttpClient, for example:
37
+		httpClient.start();						// Start HttpClient
40 38
 
41
-		CloseableHttpClient httpClient = null;
42
-		try{
43
-			httpClient = HttpClients.custom().disableAutomaticRetries().build();
39
+		// request
40
+		Request request = httpClient.newRequest(param);
41
+		request.method(HttpMethod.GET);
42
+		request.timeout(5000, TimeUnit.MILLISECONDS);
44 43
 
45
-			// parse response
46
-			HttpResponse response = httpClient.execute(httpGet);
47
-			HttpEntity entity = response.getEntity();
48
-			if (response.getStatusLine().getStatusCode() != 200) {
49
-				XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatusLine().getStatusCode());
50
-				return FAIL;
51
-			}
52
-			if (null == entity) {
53
-				XxlJobLogger.log("Http Entity Empty.");
54
-				return FAIL;
55
-			}
56
-
57
-			String responseMsg = EntityUtils.toString(entity, "UTF-8");
58
-			XxlJobLogger.log(responseMsg);
59
-			EntityUtils.consume(entity);
60
-			return SUCCESS;
61
-		} catch (Exception e) {
62
-			XxlJobLogger.log(e);
44
+		// invoke
45
+		ContentResponse response = request.send();
46
+		if (response.getStatus() != HttpStatus.OK_200) {
47
+			XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatus());
63 48
 			return FAIL;
64
-		} finally{
65
-			if (httpGet!=null) {
66
-				httpGet.releaseConnection();
67
-			}
68
-			if (httpClient!=null) {
69
-				try {
70
-					httpClient.close();
71
-				} catch (IOException e) {
72
-					XxlJobLogger.log(e);
73
-				}
74
-			}
75 49
 		}
50
+
51
+		String responseMsg = response.getContentAsString();
52
+		XxlJobLogger.log(responseMsg);
53
+		return SUCCESS;
76 54
 	}
77 55
 
78 56
 }